开发者

Do Properties have to be declared as Instance Variables in Objective C? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Properties and Instance Vari开发者_开发知识库ables in Objective-C 2.0

If I create a @property in a header file and the @synthesize it, everything seems to work fine, even if the item is not also declared as an instance variable. So why does all the example code I see declare items as both properties and instance variables?


The @property command in Objective-C 2.0 will automatically generate the instance variable for you if you have not done so. This is a shortcut introduced to limit the amount of repetitive code you have to write.

Only declare the iVar's if:

  • Need to directly access them for some advanced reason (i.e. you want to manage the memory yourself)
  • You want subclasses to be able to access the iVars (if you don't specify them at all, or specify them as @private, then subclasses will be forced to use your @synthesized accessor methods.)
  • You want your iVar to have a different name to the property itself, in which case use @synthesize myProperty = myInstanceVariable_

NOTE: If you plan to run your code on older devices or compile it with older versions, you will need to declare iVars.


No, you dont. But the autogenerated methods will try to access the instance variables, so you have to implement the setter and the getter for the property you have added.

See Vladimirs comment with the following link: Properties and Instance Variables in Objective-C 2.0

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜