Function vs Method
A function is a section of code that is called by name. It can be passed data to operate on and can optionally return data. All data that is passed to a function is explicitly passed.
A method is a section of code that is called by name that is associated with an object.
The key differences between a function and a method are:
- A method is implicitly passed the object for which it was called
- A method is able to operate on data that is contained within the class (remembering that an object is an instance of a class - the class is the definition, the object is an instance of that data)
Objective-C can handle both function and method calls. The advantage of function calls is that they are marginally quicker than method calls as you go straight to the functionality and don't have to look for the method selector in the dispatch table. The dispatch table is effectively your classes inheritance hierarchy tree (with your class at the bottom and NSObject at the top), with a method call you gradually work your way up the tree until it finds the method/selector you are interested in, it then returns and caches this method's address for future use. This caching improves return speed but still not at the level of efficiency that a function call produces.
Method call:
[objectThatContainsMethod methodName:(BOOL *)firstArg];
Function call:
void (*setter)(id, SEL, BOOL);
setter = (void (*)(id, SEL, BOOL))[target methodForSelector:@selector(methodName:)];
setter(target, @selector(methodName:), YES);
The first difference you notice is that the function takes more code and at first glance is not as pretty. Lets walk through it:
- Line 3, is acquiring the address of the method/function in dispatch tree so that it can go directly to it rather than having to check where it is each time
- You'll notice that the function call takes more arguments than its equivalent method call. This is actually not true, both take the same amount of arguments at runtime, it is just that with the method call the Objective-C runitme implicitly adds the first two arguments: id and SEL. id - calling object, SEL - selector representation of method/function. A selector actually works by storing the method name and assigning it a unique id (the same name can exist in multiple object and will all have the same id), this allows polymorphism and dynamic binding to occur. By removing this flexibility when using a function call you are tiring your code into using one implementation of a method on one specific class.