0

I need help with functions in objective C?

In C++ i can make a function like this:

int testFunction(int zahl) { 
    int loop;
    loop = zahl * 10;
    return loop;
}

this function multiply my zahl with 10 and returns the result. In C++, i can call this function whenever i want with:

testFunction(5);

and it returns 50.

I dont understand how i can make such functions like testFunction in objective c? Have I to do this with

-(void)testFunction{}?

Thankx a lot for help!!

Greez Franhu

3 Answers 3

2

Just use

int testFunction(int zahl)
{
    return zahl * 10;
}

You will only need the other notation (see user467105's answer) if you want to declare member functions.

Sign up to request clarification or add additional context in comments.

Comments

1

In Objective-C, the function can be written like this:

-(int)testFunction:(int)zahl
{
    int loop; 
    loop = zahl * 10;   
    return loop; 
}

and called like this:

int testResult = [self testFunction:5];
//assuming testFunction is in same class as current (ie. self)

However, at least in Cocoa I believe, you can have C++ and Objective-C code side-by-side so you could include the C++ version as-is and call it from Objective-C code.

2 Comments

What you've described is an Objective-C method, not a function.
Thanks a lot for your replies.. yeah i don't understand exactly the difference between function and method?
1

The function you have works exactly the same in Objective-C:

int testFunction(int zahl) { 
    int loop;
    loop = zahl * 10;
    return loop;
}

The other syntax you had:

-(void)testFunction{}?

Is for a method, in your .h file you need:

@interface SomeClass : NSObject {
}

-(int)testFunction:(int)zahl;

@end

In your .m:

-(int)testFunction:(int)zahl {
    int loop;
    loop = zahl * 10;
    return loop;
}

Then you can call it [someObjectOfTypeSomeClass testFunction:13]

Methods apply to your objects. Use methods to change or query state of objects. Use functions to do other stuff. (this is the same as C++ methods and functions)

1 Comment

Thank you! Now i can go on... ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.