views:

234

answers:

4
+2  Q: 

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?

+2  A: 

It's rougly analogous to this from C# or Me in VB. Within the scope of a class, it refers to an instantiated object of that class.

Dave Swersky
Yes it's more like a reference than a pointer: it can't (shouldn't ever) be null, and can't be reassigned to point to something else.
ChrisW
@ChrisW Why do you say it can't be reassigned to point to something else... when that's exactly what happens during initialization?
Justin
@Justin - because it `this` is not a variable. Try seeing if the compiler will let you write something like `this = ...;`.
Stephen C
@Stephen C `self` *is* a variable, and it *is* an objc idiom to assign it in initialization: `self = [super init];`.
Justin
Dreamlax's answer is quite a bit more accurate in details than this answer (which is conceptually relatively OK).
bbum
+2  A: 

A pointer like all objects!

Chris Beeson
+13  A: 

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.

dreamlax
+3  A: 

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.

Adrian