Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
145 views
in Technique[技术] by (71.8m points)

C function vs. Objective-C method?

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
}
question from:https://stackoverflow.com/questions/4846825/c-function-vs-objective-c-method

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...