开发者

About calling my properties [duplicate]

开发者 https://www.devze.com 2023-02-22 06:29 出处:网络
This questio开发者_C百科n already has answers here: Closed 11 years ago. Possible Duplicate: Difference between self.instanceVar = X and instanceVar = X in Obj-c
This questio开发者_C百科n already has answers here: Closed 11 years ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号