objective-c - 为什么这两个 "auto boxing"语句给出不同的结果?

标签 objective-c

看下面的内容,为什么 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/

相关文章:

ios - WCSession activateSession exc_bad_access 崩溃

ios - 有些表情符号的长度是 3? (数字)

ios - 在 ios 中为 MBCalendar Kit 添加事件

iphone - iOS 5 创建自定义 View

objective-c - @protocol 扩展@protocol

ios - 为什么 React Native/Objective-C 提示我用错误数量的参数调用我的方法?

ios - 如何从 didFinishPickingMediaWithInfo 返回 NSString 或 NSUrl?

ios - UIPregressView 使用 AFNetWorking 上传图片

objective-c - armv7s 可执行文件大小增加

objective-c - 使用 memcpy 和 malloc 导致数据流损坏