“getter” keyword in @property declaration in Objective-C?

混江龙づ霸主 提交于 2020-06-25 09:08:56

问题


I noticed some code example in Apple's documentation shows the following style when declaring the property:

@property (nonatomic, getter=isActivated) BOOL activated;

I understand it allows you to specify a certain name for your getter method. I'd like to know what is the reason and advantage to use this style.

Will I be able to use the dot notation to get the value (e.g. BOOL aBool = someObject.isActivated)? Or should I use
[someObject isActivated]; to access the property? Thanks!


回答1:


No, the getter keyword only changes the method name. The idea is that you'll access the property just like a variable:

if (self.activated) { ... }
self.activated = YES;

But when you're sending a message to the object, it's readable code: if ([self isActivated]) { ... }.




回答2:


Kind of the latter. You don’t have to use the method—calling someObject.activated will still work—but it lets you improve the semantics of your class’s interface. A method called -activated could return the value of the ivar activated, or it could do something more esoteric (like activating the object); isActivated clearly returns a Boolean value for whether or not the object is “activated”.



来源:https://stackoverflow.com/questions/7210937/getter-keyword-in-property-declaration-in-objective-c

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