“getter” keyword in @property declaration in Objec

2020-08-25 02:44发布

问题:

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”.