在代码中的某个时刻,我们想知道某些值的系统数据类型。因此,我们对传入的 NSNumber 进行类似其中一项的检查:
if (strcmp([numberObject objCType], @encode(NSInteger)) == 0)
{ /* tag as integer */ }
在 64 位模拟器上执行此操作并将 BOOL 放入 NSNumber 中会产生奇怪的结果。
NSNumber *foo = [NSNumber numberWithBool:YES];
if(strcmp([foo objCType], @encode(BOOL)) == 0))
{ /* this should work, but it does not on 64bit */ }
作为后备,我们可以使用类似的东西
if(strcmp([foo objCType], [[NSNumber numberWithBool:YES] objcType]) == 0))
{ /* this works, but looks like too much work for the processor */ }
针对 32 位模拟器进行编译,效果非常好。 (在这两种情况下,BOOL 看起来都像“char”类型,但在 64 位上比较并没有给出预期结果)。
那么,有人知道为什么 @encode(BOOL)
在使用 numberWithBool:
初始化时与 [foo objCType] 不匹配吗?
最佳答案
所以我做了一些研究并执行了这个:
NSNumber *foo = [NSNumber numberWithBool: YES];
NSLog(@"encode BOOL: %s", @encode(BOOL));
NSLog(@"encode boolean: %s", @encode(Boolean));
NSLog(@"encode bool: %s", @encode(bool));
NSLog(@"encode char: %s", @encode(char));
NSLog(@"object: %s", [foo objCType]);
并在 64 位模拟器中得到此结果:
encode BOOL: B
encode boolean: C
encode bool: B
encode char: c
object: c
这在 32 位模拟器上
encode BOOL: c
encode boolean: C
encode bool: B
encode char: c
object: c
所以问题是,在 32 位上,encode(BOOL) 返回“c”,但在 64 位上,它返回“B”,而 objCType
在 numberWithBool 上:
在 64 位和 32 位上都会为您提供“c”。
关于objective-c - 带有 BOOL 的 NSNumber 在 64 位上不是 BOOL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23425187/