Search code examples
iosobjective-cnsstringnsnull

Why cast to object before testing for NSNull?


I have the following block in a project I have been moved onto after a previous developer has left

NSObject *object = (NSObject *)string;
if([object isEqual:[NSNull null]])
    return @"none"

Where string is an NSString * returned from a dictionary.

While I undertand that NSNull needs to be checked for, can someone tell me why cast to NSObject first?


Solution

  • The cast is unnecessary, although it's usually best to keep an object as an id until you know it isn't an NSNull (e.g. if you just pulled it out of a collection). If you have an NSString* which might actually be NSNull it can be confusing. Perhaps the original author wanted to make it clear that the string actually could be something else?

    Also, NSNull is documented as a singleton, so you could (if you wanted) compare using ==.