为什么isKindOfClass:Nil在__NSCFConstantString上返回YES?

时间:2015-10-23 16:53:46

标签: objective-c nsobject

我遇到了一些可能会在Nil检查中使用isKindOfClass:作为类的代码,并且好奇在这种情况下会发生什么。使用Xcode 6.2,OS X 10.10 SDK并在10.9.5上运行:

for (id obj in @[
                 @"foo",
                 @"This is a long string.",
                 [NSString new],
                 [NSString stringWithUTF8String:"Hello, world!"],
                 [@"This is a constructed " stringByAppendingString:@"string."],
                 @YES,
                 @2015,
                 @[],
                 @[ @42, ],
                 @[ @"hello", ],
                 @{ @"hi": @5, },
                 ]) {
    NSLog(@"[obj className] => %@; [obj isKindOfClass:Nil] => %@", [obj className], [obj isKindOfClass:Nil] ? @"YES" : @"NO");
}

产生

[obj className] => __NSCFConstantString; [obj isKindOfClass:Nil] => YES
[obj className] => __NSCFConstantString; [obj isKindOfClass:Nil] => YES
[obj className] => __NSCFConstantString; [obj isKindOfClass:Nil] => YES
[obj className] => __NSCFString; [obj isKindOfClass:Nil] => NO
[obj className] => __NSCFString; [obj isKindOfClass:Nil] => NO
[obj className] => __NSCFBoolean; [obj isKindOfClass:Nil] => NO
[obj className] => __NSCFNumber; [obj isKindOfClass:Nil] => NO
[obj className] => __NSArrayI; [obj isKindOfClass:Nil] => NO
[obj className] => __NSArrayI; [obj isKindOfClass:Nil] => NO
[obj className] => __NSArrayI; [obj isKindOfClass:Nil] => NO
[obj className] => __NSDictionaryI; [obj isKindOfClass:Nil] => NO

为什么[obj isKindOfClass:Nil]会为YES个对象返回__NSCFConstantString而没有其他任何内容(或者,至少我没有尝试过其他内容)?

编辑: 最终,我正在处理的代码中的解决方案是防止在类Nil时发生调用,所以这问题实际上只是一种好奇心,特别是因为iOS 9.1和OS X 10.11.1上的行为不同(根据评论)。

0 个答案:

没有答案