iOS - beginning iOS tutorial - underscore before variable?

家住魔仙堡 提交于 2019-12-05 05:14:30

The reason statusLabel.text = plainText; failed is because you were not accessing the property correctly. In order to access it through the generated getters/setters, you need to prepend self. to it, as the property (and its setters/getters) belongs to the instance of self. So instead it would be self.statusLabel.text = plainText;

The reason _statusLabel worked is because this is the underlying variable that holds the value for the property. You are circumventing the generated setters/getters when accessing the variable this way. Generally, you should use self.propertyName, as this will respect the keywords you have provided as part of the property definition (a good example is if you use the atomic keyword, as the generated setters and getters will correctly place a @synchronized block around the underlying instance variable).

Recent versions of Xcode create the variable name with a prepended underscore if you don't manually synthesize your properties (which is an OK thing to do, previously people had to synthesize manually). You can define your own underlying variable name if you so wish, using @synthesize statusLabel = m_statusLabel. This mean you can access it using m_statusLabel instead of _statusLabel. You shouldn't need to do this usually, unless there is a dire need to; Apple suggests using a prepended underscore.

You should use the underlying variable when in initialising methods, and deallocating methods, as the generated setters/getters may not be complete when at this point in the code.

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