Enrique
Enrique

Reputation: 882

Does the execution of Objective-C methods create "frames on the stack"?

I know that, in C, each function creates a frame and each frame is automatically deallocated when the function using it ends. Does the same logic apply to Objective-C methods? Do they create frames on the stack when executed?

Upvotes: 2

Views: 134

Answers (1)

NobodyNada
NobodyNada

Reputation: 7634

Yes, they do.


Objective-C calls methods dynamically, so:

[someObject doSomething];

is equivalent to:

objc_msgSend(someObject, sel_registerName("doSomething"));

sel_registerName returns a selector, which is basically a method identifier, for the given method name.

objc_msgSend is written in assembly, and the code is available here. It looks up the selector in the object's list of methods. The method list contains an IMP for the selector doSomething, which is a C function pointer to a function similar to:

void doSomething(id self, SEL _cmd);

objc_msgSend then tail-calls the function pointer,

So methods are just regular C functions, but they are called dynamically at runtime. When objc_msgSend is called, the return address is pushed onto the stack and the CPU jumps to objc_msgSend. It doesn't look like objc_msgSend touches the stack at all, so the method sets up a stack frame just as like C function. When it's done, the method tears down it's stack frame and returns exactly as a C function would. Since objc_msgSend left the stack untouched, it returns directly to the code which called the method, exactly as if the method implementation was directly called.

Upvotes: 5

Related Questions