计算中的BOOL属性使用valueForKey返回带有错误值的NSNumber: [英] BOOL property from a calculation returns NSNumber with incorect value using valueForKey:

查看:87
本文介绍了计算中的BOOL属性使用valueForKey返回带有错误值的NSNumber:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的对象,其中有一个NSNumber用于存储一些标志. 我有一个conienience getter方法,实际上可以做到:

I have a simple object which has one NSNumber which is used to store some flags. I have a conienience getter method which in fact does:

[self.flags integerValue] & SomeConstantFlag

属性@property (readonly, nonatomic, assign) BOOL someConstantFlag

,并且在访问基本的bool值(如

and this works fine when accesing the underlying bool value like

model.someConstantFlag

但是当我尝试

id value = [model valueForKey:@"someConstantFlag"];

然后返回错误的布尔表示形式,例如NSNumber的值为2、4等 当属性的声明为BOOL时,为什么会发生这种情况?有没有一种漂亮"的方法可以解决此问题?

Then it returns a bad boolean representation e.g. NSNumber with value 2, 4 etc. Why is this happening when the declaration of the property is BOOL? Is there a "Pretty" way to overcome this issue?

另一方面,包裹可以正常工作

Wrapping on the other hand works ok:

BOOL someBool = 42;
NSNumber* numberVal = @(someBool);
//The underlying is an __NSCFBoolean with the proper 0/1 val!

推荐答案

valueForKey始终返回一个Objective-C对象,即使该属性具有标量类型也是如此.

valueForKey always returns an Objective-C object, even if the property has scalar type.

来自文档 (强调我的):

valueForKey:setValue:forKey:的默认实现 为非对象数据的自动对象包装提供支持 标量和结构类型.

The default implementations of valueForKey: and setValue:forKey: provide support for automatic object wrapping of the non-object data types, both scalars and structs.

一旦valueForKey:确定了特定的访问器方法,或 用于提供指定值的实例变量 键,它检查返回类型或数据类型.如果值是 返回的不是对象,已创建NSNumberNSValue对象 并返回该值.

Once valueForKey: has determined the specific accessor method or instance variable that is used to supply the value for the specified key, it examines the return type or the data type. If the value to be returned is not an object, an NSNumber or NSValue object is created for that value and returned in its place.

您的方法的返回值为BOOL,其定义为

The return value of your method is BOOL, which is defined as

typedef signed char BOOL;

在OS X和32位iOS平台上

.所以valueForKey返回的是NSNumber 包含

on OS X and on the 32-bit iOS platform. So what valueForKey returns is a NSNumber containing the result of

signed char val = [self.flags integerValue] & SomeConstantFlag;

,该范围可以是-128 .. 127.

and that can be in the range -128 .. 127.

为确保只得到YESNO(又名1或0),请编写自定义吸气剂为:

To ensure that you get only YES or NO (aka 1 or 0) write your custom getter as:

-(BOOL)someConstantFlag
{
    return ([self.flags integerValue] & SomeConstantFlag) != 0;
}

备注:在64位iOS平台上(但在64位OS X上不是),BOOL定义为C99 _Bool,它是适当的"布尔类型.并且只能取值0或1.

Remark: On the 64-bit iOS platform (but not on 64-bit OS X), BOOL is defined as the C99 _Bool, which is a "proper" boolean type and can take only the value 0 or 1.

这篇关于计算中的BOOL属性使用valueForKey返回带有错误值的NSNumber:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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