设置 BOOL 属性的正确方法 [英] Correct way of setting a BOOL property

查看:157
本文介绍了设置 BOOL 属性的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 BOOL 属性,我想在我的类初始值设定项中设置它.

I have a BOOL property that I want to set in my class initializer.

@property (assign, nonatomic) BOOL isEditMode; 

- (id)init
{
    . . . 
    [self setValue:NO forKey:isEditMode];
    return self;
}

编译器给我一个不兼容的整数到指针转换"警告.我在这里做错了什么?

The compiler gives me an "Incompatible integer to pointer conversion" warning. What am i doing wrong here?

推荐答案

键值编码方法 setValue:forKey: 只接受对象作为参数.要设置 BOOL,您需要使用 [NSNumber numberWithBool:NO] 将数字包装在一个值对象中.但没有什么理由这样做.键值编码是实现此目的的一种迂回方式.要么做 self.isEditMode = NO,要么就做 isEditMode = NO.后者在 init 方法中更可取(因为 setter 可以运行在对象完全设置之前可能不需要的任意代码).

The Key-Value Coding method setValue:forKey: only accepts objects as arguments. To set a BOOL, you need to wrap the number in a value object with [NSNumber numberWithBool:NO]. But there's little reason to do that. Key-Value Coding is a roundabout way to accomplish this. Either do self.isEditMode = NO or just isEditMode = NO. The latter is preferable in an init method (because setters can run arbitrary code that might not be desirable before an object is fully set up).

但是要详细说明第一点:键值编码以这种方式工作的原因是因为类型系统无法表示有时是对象而有时是原始值的参数.所以 KVC 总是处理对象,并根据需要自动装箱原始值.类似地,如果你执行 [yourObject valueForKey:@"isEditMode"],你会得到一个包含真实值的 NSNumber 对象.

But to elaborate on the first point: The reason Key-Value Coding works this way is because the type system can't represent an argument that's sometimes an object and at other times a primitive value. So KVC always deals with objects and just autoboxes primitive values as necessary. Similarly, if you do [yourObject valueForKey:@"isEditMode"], you'll get back an NSNumber object wrapping the real value.

这篇关于设置 BOOL 属性的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆