C function vs. Objective-C method?

前端 未结 3 1344
清酒与你
清酒与你 2020-12-13 04:24

What is the difference between the two? If I\'m writing a program, when would I need a this:

void aFunction() {
    //do something
}

and wh

相关标签:
3条回答
  • 2020-12-13 04:31

    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.

    0 讨论(0)
  • 2020-12-13 04:43

    In Objective-C each function operates on an object, like

    [myObject myFunction]

    A C method has the form:

    return-type function-name(argument1, argument2, etc) {}

    An Objective-C instance method has the form:

    -(return-type)function-name:argument1 {}

    or for a multi-argument function

    -(return-type)function-name:argument1 function-name:argument2 {}

    I always use Objective-C-style methods in Obj-C programming, even though you can still use C-type functions as well.

    I suppose the equivalent in C to [myObject myMethod:arg] might be myObject.myMethod(arg)

    0 讨论(0)
  • 2020-12-13 04:55

    The first is a freestanding function. The second is an instance method for an Objective-C class. So I guess you would need the second version if you're actually writing a class.

    0 讨论(0)
提交回复
热议问题