使用 BOOL 属性

苹果公司建议以这种方式声明 BOOL 属性:

@property (nonatomic, assign, getter=isWorking) BOOL working;

因为我使用 Objective-C2.0属性和点符号,所以我使用 self.working访问这个属性。我知道我也可以使用 [self isWorking]ーー但是我没有必要这样做。

因此,既然我在任何地方都使用点表示法,为什么要定义额外的属性呢?可以简单地写下

@property (nonatomic, assign) BOOL working;

或者在我的情况下编写 getter=isWorking有什么好处(使用点符号) ?

谢谢!

113123 次浏览

Apple simply recommends declaring an isX getter for stylistic purposes. It doesn't matter whether you customize the getter name or not, as long as you use the dot notation or message notation with the correct name. If you're going to use the dot notation it makes no difference, you still access it by the property name:

@property (nonatomic, assign) BOOL working;


[self setWorking:YES];         // Or self.working = YES;
BOOL working = [self working]; // Or = self.working;

Or

@property (nonatomic, assign, getter=isWorking) BOOL working;


[self setWorking:YES];           // Or self.working = YES;, same as above
BOOL working = [self isWorking]; // Or = self.working;, also same as above

There's no benefit to using properties with primitive types. @property is used with heap allocated NSObjects like NSString*, NSNumber*, UIButton*, and etc, because memory managed accessors are created for free. When you create a BOOL, the value is always allocated on the stack and does not require any special accessors to prevent memory leakage. isWorking is simply the popular way of expressing the state of a boolean value.

In another OO language you would make a variable private bool working; and two accessors: SetWorking for the setter and IsWorking for the accessor.

Apple recommends for stylistic purposes.If you write this code:

@property (nonatomic,assign) BOOL working;

Then you can not use [object isWorking].
It will show an error. But if you use below code means

@property (assign,getter=isWorking) BOOL working;

So you can use [object isWorking] .