Reputation: 820
I have been making iPhone apps for a couple of month now and i still haven't really understand what self does. I know its a pointer to the receiver but that doesn't really tell me anything. I think i would understand it more if someone show me an example when i should use it and explain what would happened if i not use it. I have only been using self for calling methods.
[self myMethod]
// calling a method
Third and last question: what can I call self on expect properties and methods?
Upvotes: 0
Views: 146
Reputation: 62052
In a class method, self
is a pointer to the class.
In an instance method, self
is a pointer to an instantiated object of the class.
Let's focus on the latter, as it's the most common use of self
.
Let's suppose we have a Box
class. When we want to represent a box programmatically, we instantiate an instance of the Box
class:
Box *myBox = [[Box alloc] init];`
Now, we can instantiate as many instances of boxes as we'd like.
Box *greenBox = [[Box alloc] init];
Box *redBox = [[Box alloc] init];
Box *blueBox = [[Box alloc] init];
Now, within the Box
class, we will have instance methods. These are methods that are called on instantiated objects of Box
. For example:
[greenBox someMethod];
[redBox someOtherMethod];
But this is an outside with a reference to a box that wants to call a method on a specific Box reference.
When a Box object needs to call a method on itself, it uses self
as a reference to itself.
So, let's say when someMethod
is called on a Box object, as part of someMethod
, the Box object needs to call a method doStuff
on itself.
So in Box.m
, we might have:
- (void)someMethod {
// doing actual stuff, then calling a method to do stuff
[self doStuff];
}
Where self
is another method within this file and we're calling it on the object for which the someMethod
message was sent to.
This would be like the outside caller saying [greenBox doStuff];
.
But we can use self
in other ways.
We can use self
to access properties of the object. For example, consider this property in Box.h
,
@property BOOL canDoStuff;
Now back to someMethod
:
- (void)someMethod {
// doing actual stuff then...
if (self.canDoStuff) {
[self doStuff];
}
}
And we can also use self
as a method argument. For example:
- (void)someMethod {
// doing actual stuff then...
if (self.canDoStuff) {
[BoxHelperClass doStuffWithABox:self];
}
}
Upvotes: 3