About calling my properties [duplicate]
Possible Duplicate:
Difference between self.instanceVar = X and instanceVar = X in Obj-c
@interface Whatever : Something
{
DPad *dPad;
}
@property (retain) DPad *dPad;
@end
And then I synthesize:
@synthesize dPad;
I noticed I can all my dPad with
self.dPad
and just
dPad
Is there any difference? I can use any? If I used both for whatever reason, both would affect the same object, right?
Yes there is a difference. self.dPad calls the getter method for dPad, whereas dPad just accesses the instance variable directly. If you override the getter, any additional checking or setup, or memory management you might do in the getter will not be called. As a good practice, it's probably better to call the getter, than access directly, even if you're just synthesizing and not overriding.
One accesses the property directly, the other uses the accessors.
Directly accessing an instance variable was possible long before Apple invented the dot-syntax for properties.
self.dPad
get rewritten transparently by the compiler:
self.dPad = someOtherDPad;
[self setDPad:someOtherDPad];
// or for getters
[self.dPad doSomething];
[[self getDPad] doSomething];
Using the properties and the accessors allows for more flexibility, for example Key-Value-Observing is only possible using the accessors. The downside is a small loss of performance, which you shouldn't notice in most cases.
精彩评论