Is a pointer?

What is this self ? Is it right to call a pointer? Or is it a variable? Or what else?

+4
source share
4 answers

The implementation of the Objective-C method is actually just a C function that takes two additional arguments. The first argument is the self variable, and the second argument is the selector that was used to invoke the implementation. The third and any subsequent arguments (if any) are the actual arguments to your method. If you have a method like this:

 @implementation MyClass - (int) myMethod:(int) anArg { NSLog (@"The selector %@ was used.", NSStringFromSelector(_cmd)); return [self someValue] + anArg; } @end 

Then it is roughly equivalent to this:

 // Implementation of MyClass instance method "myMethod" int MyClass_myMethod (id self, SEL _cmd, int anArg) { NSLog (@"The selector %@ was used.", NSStringFromSelector(_cmd)); return [self someValue] + anArg; } 

Keep in mind that calling a C function and sending a message are very different. Sending a message to an object will cause an implementation call, and this implementation is determined by the execution time. Since the implementation of the method is determined at runtime, the compiler cannot just swap out all message sending with direct function calls. I believe that there are ways to tell the runtime to change which method implementation to use for a given selector for a given class.

Runtime determines which implementation to use based on the self class. If self is nil , sending the message is a non-statement, so all implementations of the method will always have a valid value for self when they are called by the runtime.

+15
source

self actually defined on NSObject :

 - (id)self; 

So self is of type id , which is again defined in the Objective-C runtime:

 typedef struct objc_object { Class isa; } *id; 

So yes, self is just a pointer to an Objective-C object.

See the init method documentation for more information.

+5
source

It is similar to this from C # or Me in VB. Within a class, it refers to an instance of an object of this class.

+2
source

Pointer, like all objects!

+2
source

All Articles