Gowtham
Gowtham

Reputation: 117

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

In these both cases the NSString has not been NIL. In first case it has been failure.Can you anyone please explain me about these?

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

Upvotes: 1

Views: 63

Answers (2)

Nikolai Ruhe
Nikolai Ruhe

Reputation: 81858

Why do these output differ?

Nil is not a class object that you can use with isKindOfClass:. As the documentation does not say anything about passing Nil it's just undefined. In my experiments I always get YES but the result might be just random.

If you want to check if a variable is nil just use plain old C equality:

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

Upvotes: 4

Teja Nandamuri
Teja Nandamuri

Reputation: 11201

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.

If you want to check whether string is nil or not, you can simply do this:

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

Upvotes: 0

Related Questions