开发者

Using setters On Int?

Just curious, given:

unsigned int pulseCounter_001;
@property(nonatomic, assign)unsigned int pulseCounter_001;
@synthesize pulseCounter_001;

Is there any reason to use:

[self setPulseCounter_001:0];

Or just use:

pulseCounter_001 = 0;

Style wise I think开发者_开发知识库 the latter says "we are setting an int" better, just curious as to any overheads involved in each?

gary


The former uses the generated setter method to set your integer. This has a small performance penalty caused by the method call, but is generally considered better since it encapsulates your data access.

For example, if you wanted to log something every time you set a new value to this integer, you could do so in the setter method. Encapsulation is good, you should use it.

As mentioned by others, KVO is another very good reason to use properties.


Another good reason to use the setter is to support KVO.


The former is KVC compliant and will notify every KVC observer that the value of pulseCounter_001 has changed. The latter is not KVC compliant and will not notify the observers of the value change.

Thus, if you have KVC observers or bindings to pulseCounter_001 the latter will not work with them.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜