看下面的内容,为什么 c_obj 不是 __NSCFBoolean 类,而 b_obj 是? b 和 c 之间的唯一区别是否定运算符。我
BOOL a = ![[NSNumber numberWithInt:1] boolValue];
id a_obj = @(a);
NSLog(@"a_obj class: %@", [a_obj class]); // class is __NSCFBoolean
// This one behaves the same as a
id b_obj = @([[NSNumber numberWithInt:1] boolValue]);
NSLog(@"b_obj class: %@", [b_obj class]); // class is __NSCFBoolean
// But not this one, even though it is pretty much the same
id c_obj = @(![[NSNumber numberWithInt:1] boolValue]);
NSLog(@"c_obj class: %@", [c_obj class]); // class is __NSCFNumber ?!?
提前致谢!
编辑:
如果我转换为 BOOL,它可以解决问题。
// A cast "fixes" it
id d_obj = @((BOOL)![[NSNumber numberWithInt:1] boolValue]);
NSLog(@"d_obj class: %@", [d_obj class]); // class is __NSCFBoolean
最佳答案
逻辑否定运算符 (!
) 的类型是 (Objective-)C 中的 int
。由于这是与 BOOL
不同的类型,因此编译器以不同方式包装它也就不足为奇了。
关于objective-c - 为什么这两个 "auto boxing"语句给出不同的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28508025/