What is self in ObjC? When should i use it?

What does self mean in Objective-C? When and where should I use it? Is it similar to this in Java?


self refers to the instance of the current class that you are working in, and yes, it is analagous to this in Java.

You use it if you want to perform an operation on the current instance of that class. For example, if you are writing an instance method on a class, and you want to call a method on that same instance to do something or retrieve some data, you would use self:

int value = [self returnSomeInteger];

This is also often used for accessor methods on an instance (i.e. setters and getters) especially with setter methods, if they implement extra functionality rather than just setting the value of an instance variable, so that you do not have to repeat that code over and over when you want to set the value of that variable, for example:

[self setSomeVariable:newValue];

One of the most common uses of self is during initialization of a class. Sample code might look like:

- (id)init
{
    self = [super init];

    if(self!=nil) {
        //Do stuff, such as initializing instance variables
    }

    return self;
}

This invokes the superclass's (via super) initializer, which is how chained initialization occurs up the class hierarchy. The returned value is then set to self, however, because the superclass's initializer could return a different object than the superclass.


self is an implied argument to all Obj-C methods that contains a pointer to the current object in instance methods, and a pointer to the current class in class methods.

Another implied argument is _cmd, which is the selector that was sent to the method.

Please be aware that you only get self and _cmd in Obj-C methods. If you declare a C(++) method, for instance as a callback from some C library, you won't get self or cmd.

For more information, see the Using Hidden Arguments section of the Objective-C Runtime Programming guide.


Yes, it's exactly the same as "this" in Java - it points to the "current" object.