26

Is there any dramatic difference between functions and methods in Objective -C?

NCFUSN
  • 1,624
  • 4
  • 28
  • 44

2 Answers2

74

First, I'm a beginner in Objective-C, but I can say what I know.

Functions are code blocks that are unrelated to an object / class, just inherited from c, and you call them in the way:

// declaration
int fooFunction() {
    return 0;
}

// call
int a;
a = fooFunction();

While methods are attached to class / instance (object) and you have to tell the class / object to perform them:

// declaration
- (int)fooMethod {
    return 0;
}

// call
int a;
a = [someObjectOfThisClass fooMethod];
MByD
  • 135,866
  • 28
  • 264
  • 277
6

It is even simpler; a method is just a C function with the first two argument being the target of the method call and the selector being called, respectively.

I.e. every single method call site can be re-written as an equivalent C function call with absolutely no difference in behavior.


In depth answer here: Why [object doSomething] and not [*object doSomething]? Start with the paragraph that says "Getting back to the C preprocessor roots of the language, you can translate every method call to an equivalent line of C".

Community
  • 1
  • 1
bbum
  • 162,346
  • 23
  • 271
  • 359
  • that's interesting - can you show an example of that, and in which step it's converted to a simple function call? also, can you point me to some materials about that? – MByD Jul 12 '11 at 23:51