当我尝试在 Objective C 中执行 isKindOfClass 时,为什么这些输出不同?

Why do these output differ while I try to execute the isKindOfClass in Objective C?

在这两种情况下,NSString 都不是 NIL。在第一种情况下是 failure.Can 你有人请解释一下这些吗?

NSString *str1 = @"str";
if (![str1 isKindOfClass:Nil]) {
    NSLog(@"true");
}
NSString *str2 = [NSString stringWithFormat:@"str"];
if (![str2 isKindOfClass:Nil]) {
     NSLog(@"true");
}

isKindOfClass

Returns a Boolean value that indicates whether the receiver is an instance of given class or an instance of any class that inherits from that class.

如果你想检查字符串是否为 nil,你可以简单地这样做:

if(str1){
        NSLog(@"string is not nil");
    }

Why do these output differ?

Nil 不是可以与 isKindOfClass: 一起使用的 class 对象。由于文档没有说明有关传递 Nil 的任何内容,因此它只是未定义。在我的实验中,我总是得到 YES 但结果可能只是随机的。

如果你想检查一个变量是否为 nil 只需使用普通的旧 C 相等:

NSString *str1 = @"str";
if (str1 != nil) {           // explicit
    NSLog(@"true");
}
NSString *str2 = [NSString stringWithFormat:@"str"];
if (str2) {                  // or just like this
    NSLog(@"true");
}