Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smalltalk-style Messages vs. C-style Functions

When should I use messages versus C-style functions?

like image 214
Jake Avatar asked May 05 '09 18:05

Jake


2 Answers

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);
like image 108
e.James Avatar answered Oct 02 '22 16:10

e.James


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.

like image 28
Charlie Martin Avatar answered Oct 02 '22 16:10

Charlie Martin