views:

317

answers:

3

When should I use messages versus C-style functions?

+4  A: 

Objective-c makes that distinction for you. Messages must be sent to objects, but functions can be used at any time.

messages:

Objective-C messages can only be sent to objects, and the messaging system is the way to make calls to the methods of a class.

Example:

// a class interface definition
// including a method named aMethod
@interface ANObject
{

}
- (void)aMethod;
@end


// a message sent to that object:
ANObject * myObject = [[ANObject alloc] init];
[myObject aMethod]; // <-- message
[myObject release];

functions:

Objective-C inherits all of the C language, so C-style function calls are supported, and even encouraged, when the situation calls for them. Objective-C objects are simply passed around as pointers, so you can still pass them to functions as arguments. The usual cautions and rules about passing pointers to functions should, of course, be respected.

Example:

// a regular C-style function
void someFunction(ANObject * argument)
{
    // do something here...
}


// and how to call it:
someFunction(someObject);

when to use each?

Use messages/methods when you want to access some propery of an object/class. Good examples would be accessing the length of an NSString:

int stringLength = [myString length];

Setting a value of a property:

[myObject setHidden:YES];

Or telling an object to perform some task:

[myAccount withdrawMoneyAndDriveToMexico];

Use C-style functions when you want to perform a task that does not belong to a class; something that should stand alone. Good examples would be mathematical functions such as:

double degrees = ConvertRadiansToDegrees(radians);
e.James
Thanks for your post.
Jake
+2  A: 

Basically, use messages any time you're dealing with an Objective C component; more or less any time you are using an NS* type.

Under the covers you're essentially using C function calls in any case; the original implementation of Objective C was a preprocessor to C. But the whole point of using Objective C is to get the Smalltalk like syntax, which is what you have anywhere inside []'s.

Charlie Martin
+1  A: 

You've asked a lot of Java questions; perhaps a Java analogy will help. Where one would use a method in Java, use a message in Objective-C. Where one would use a static method in Java, use a class method in Objective-C. If you would find yourself creating utility packages in Java that are full of static methods, that is something that might be make sense as a function in Objective-C.

And, of course, it may make sense if you are doing weird Objective-C++ stuff as well.

Matt Kane