What is the difference between the two? If I'm writing a program, when would I need a this:
void aFunction() { //do something }
and when would I need this:
-(void)aMethod { //do something else }
The difference between C and Objective C is speed. But this call needs to perform a dynamic look-up in a method table and that every time the method is called. C on the other hand does static dispatch. Static dispatch is much faster.
You really can't use C in Objective-C, since Objective-C is C. The term is usually applied when you write code that uses C structures and calls C functions directly, instead of using Objective-C objects and messages.
Basically in Objective-C, we call the function as method. The Objective-C foundation framework provides numerous built-in methods that your program can call. For example, method appendString() to append string to another string. A method is known with various names like a function or a sub-routine or a procedure, etc.
Actually, an Objective-C method is just a C function with two arguments always present at the beginning.
This:
-(void)aMethod;
Is exactly equivalent to this:
void function(id self, SEL _cmd);
Objective-C's messaging is such that this:
[someObject aMethod];
Is exactly equivalent to this (almost -- there is a variadic argument ABI issue beyond the scope of this answer):
objc_msgSend(someObject, @selector(aMethod));
objc_msgSend() finds the appropriate implementation of the method (by looking it up on someObject
) and then, through the magic of a tail call optimization, jumps to the implementation of the method which, for all intents and purposes, works exactly like a C function call that looks like this:
function(someObject, @selector(aMethod));
Quite literally, Objective-C was originally implemented as nothing but a C preprocessor. Anything you can do in Objective-C could be rewritten as straight C.
Doing so, however, would be a complete pain in the ass and not worth your time beyond the incredibly educational experience of doing so.
In general, you use Objective-C methods when talking to objects and function when working with straight C goop. Given that pretty much all of Mac OS X and iOS provide Objective-C APIs -- certainly entirely so for the UI level programming entry points -- then you use Obj-C most of the time.
Even when writing your own model level code that is relatively standalone, you'll typically use Objective-C simply because it provides a very natural glue between state/data & functionality, a fundamental tenant of object oriented programming.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With