views:

67

answers:

3

Hi guys!

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

+1  A: 

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.

aBitObvious
What you've described is an Objective-C *method*, not a function.
jlehr
@jlehr: Yes, you're right.
aBitObvious
Thanks a lot for your replies.. yeah i don't understand exactly the difference between function and method?
+2  A: 

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.

swegi
A: 

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)

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