Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is self a pointer?

What kind of thing is self? Is it correct to call it a pointer? Or is it a variable? Or what else?

like image 394
openfrog Avatar asked Nov 29 '22 11:11

openfrog


2 Answers

An Objective-C method implementation is really just a C function that takes two extra 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's 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 though, that calling a C function and sending a message are very different. Sending a message to an object will cause invocation of an implementation, and that implementation is determined by the run-time. Since the method implementation is determined at run-time, the compiler cannot simply swap all the message-sending with straight function calls. I believe there are ways to tell the run-time to alter which method implementation to use for a given selector for a given class.

The run-time determines which implementation to use based on the class of self. If self is nil, the message-sending is a no-op, therefore, all method implementations will always have a valid value for self when they are invoked by the run-time.

like image 162
dreamlax Avatar answered Dec 12 '22 08:12

dreamlax


self is actually defined on NSObject:

- (id)self;

So self is of type id, which again is 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 documentation of the init method for more information.

like image 36
Adrian Avatar answered Dec 12 '22 06:12

Adrian