"getter" keyword in @property declaration in Objective-C?
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 s开发者_运维技巧pecify 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!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]) { ... }
.
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”.
精彩评论