The Keyword self
A common situation is that code in an instance method defined in a class must call another instance method defined within the same class. We have not yet discussed how to do this. A method is called by sending a message to an object; in this situation, what object would that be? The answer is supplied by a special keyword, self. Here’s a simple example:
@implementation MyClass
- (NSString*) greeting {
return @"Goodnight, Gracie!";
}
- (NSString*) sayGoodnightGracie {
return [self greeting];
}
@endWhen the sayGoodnightGracie message is sent to a MyClass instance, the sayGoodnightGracie method runs. It sends the greeting message to self. As a result, the greeting instance method is called; it returns the string @"Goodnight, Gracie!", and this same string is then returned from the sayGoodnightGracie method.
The example seems straightforward enough, and it is. In real life, your code when you define a class will sometimes consist of a few public instance methods along with lots of other instance methods on which they rely. The instance methods within this class will be calling each other constantly. They do this by sending messages to self.
Behind this simple example, though, is a subtle and important mechanism having to do with the real meaning of the keyword self. The keyword self does not actually mean “in the same class.” It’s an instance, after all, not a class. What instance? It’s this same instance. The same as what? The same instance to which the message was sent ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access