0

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.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Weakman10122
  • 371
  • 2
  • 14
  • I would write it like this: `id obj = dic[@"text"]; if ([objc isKindOfClass: [NSString class]]) {etc}`. But be aware when testing against class clusters: http://stackoverflow.com/questions/1096772/is-it-safe-to-use-iskindofclass-against-an-nsstring-instance-to-determine-type – koen May 06 '17 at 15:38
  • 1
    That class cluster warning is interesting side note, but it is really not applicable here. Besides, the two top answers to that question have seriously misunderstood Apple's point. Apple is merely advising that if you have some interface that prescribes that an object will be of one type, that you should abide by that contract and you shouldn't then test to see if, behind the scenes, it is really another of the cluster's types and try to take advantage of that. In this case, there is no such contract. – Rob May 06 '17 at 16:33
  • By the way, you can use `dic[@"text"]`. – Sulthan May 06 '17 at 17:25

1 Answers1

3

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.

Sulthan
  • 128,090
  • 22
  • 218
  • 270
rmaddy
  • 314,917
  • 42
  • 532
  • 579