What does self
mean in Objective-C? When and where should I use it?
Is it similar to this
in Java?
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.