Objective C - Synthesize property [duplicate]

吃可爱长大的小学妹 提交于 2020-01-18 05:46:09

问题


Possible Duplicate:
Prefixing property names with an underscore in Objective C

When synthesizing properties I found out that someone is doing:

@synthesize myVar = _myVar;

what is "_myVar" and which is the difference with simply doing :

@synthesize myVar;        

Lastly when I should prefer the first solution to the last one?

Thanks Luca


回答1:


What _myVar really is in your example, is the name of the ivar that is backing your property. By default, when you synthesize a property, an ivar of the same name is created for you. So, you can use your property to set your ivar through setter/getter or the _myVar to directly access your variable (bypassing KVC/KVO of course).

EDIT: From Apple's Coding Guidelines for Cocoa

...In many cases, when you use a declared property you also synthesize a corresponding instance variable.

Make sure the name of the instance variable concisely describes the attribute stored. Usually, you should not access instance variables directly, instead you should use accessor methods (you do access instance variables directly in init and dealloc methods). To help to signal this, prefix instance variable names with an underscore (_)...




回答2:


If you want to use some existing data member in setter and getter then it can be specify like that.

e.g. @synthesize personName=pName;

by this we can use pName instead of personName as per our convenience.




回答3:


It the name of the private variable.

Se my answer on an other post: answer



来源:https://stackoverflow.com/questions/10651535/objective-c-synthesize-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!