Weakman10122
Weakman10122

Reputation: 391

Objective-C: If an object belongs to a class, does this mean the object isn't nil or null as well?

The code below is what I had before in my app.

Before:

  if ([dic objectForKey:@"text"] isKindOfClass:[NSString class]] && [dic objectForKey:@"text"] != nil && [dic objectForKey:@"text"] != [NSNull Null]) {
       NSString *text = [dic objectForKey:@"text"];
    }

I've changed the code to the following below.

After:

    if ([dic objectForKey:@"text"] isKindOfClass:[NSString class]]) {
        NSString *text = [dic objectForKey:@"text"];
    }

I believe the results should be the same ,but the latter is neater. Just to be safe, I am asking this question to make sure I'm right about this and not overlooking anything.

Upvotes: 0

Views: 54

Answers (1)

rmaddy
rmaddy

Reputation: 318854

Your simpler code will work.

If [dic objectForKey:@"text"] is nil, then the call to isKindOfClass isn't even called and effectively a result of false is returned.

If [dic objectForKey:@"text"] is not nil, then it must be an NSString to be true so there's no need to check to see if it is NSNull.

In other words, if [[dic objectForKey:@"text"] isKindOfClass:[NSString class]] is true, then you already know that it wasn't nil and you already know that it isn't NSNull, so those checks are not needed.

Upvotes: 3

Related Questions