2

Possible Duplicate:
Objective C message dispatch mechanism

My question IS NOT about the syntax. I'd like to learn how is calling a method in C++ different from sending a message to an object in Objective-C and how they are performed?

Community
  • 1
  • 1
Roman
  • 10,309
  • 17
  • 66
  • 101

2 Answers2

6

This is quite a complicated question, as there is no fix C++ calling convetion unlike C.

Objective-C is just a thin wrapper around C, so it uses the same convention. Just one additional thing to now, when you send a message like:

[target selector];

It is the same as:

objc_msgSend(target, @selector(selector));

Then it's just the traditional C calling convention, with a first table lookup for the function matching your message. The objc_msgSend is a bit more complicated as it keeps the arguments stack in place and pass it directly to the underlying function.

The C++ calling convention differs from one name-mangling to another, and even from one compiler to another.

From a performance point of view, C++ method call is faster as the link is resolved at compile-time (more exactly at link-time). The method either exists or not, which cause a linker error.

Objective-C method call include a method table lookup at runtime, thus your method may be added later in your code, which gives more flexibility but less performance.

Jaffa
  • 12,442
  • 4
  • 49
  • 101
  • is this also the reason for why the "this" keyword in Obj-C method is actually a hidden parameter of the method? – Roman Dec 20 '11 at 01:59
  • objc_msgSend is a function not a method, and as far as I know, the this keyword simply does not exists in Obj-C, as self does the same job. It permits to use Obj-C++, where this has a utility. – Jaffa Dec 20 '11 at 02:02
  • O yes, I meant to say self not this. Too used to C# and C++ convention! – Roman Dec 20 '11 at 02:04
  • 1
    Then yes, it's an hidden parameter, but it may be the same for C++ (depending on the compiler, again), as the method definition remains the same whatever object use it. So the self or this variable is or respectively may be passed as argument. Using this method you can also do some (kind of) OOP in C, even if this is not really useful :) – Jaffa Dec 20 '11 at 02:07
-2

Entirely the same and entirely different. In C++ you'd say

result = myObjectPtr ->myMethod(myParm1, myParm2);

In Objective-C you'd say

result = [myObjectPtr myMethodWithParm1:myParm1 andParm2:myParm2];

In the simple case they'd function the same, from an external appearances standpoint, but lots of differences at the implementation level, since Objective-C calls are dynamic.

It would take several pages to enumerate all the differences in any detail (though for the simplest cases the differences aren't significant).

Hot Licks
  • 47,103
  • 17
  • 93
  • 151