Question

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?

Was it helpful?

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 ==.

OTHER TIPS

Actually in your case you no need to type cast string (if it is object of NSString class) to NSObject. Anyways, NSObject is an root class in Objective-C so it can be all type objects. NSString class also inherit from NSObject. So NSObject *object = (NSObject *)string also valid.

if([string isEqual:[NSNull null]])
    return @"none"

Also work for you.

The best practice keep your object in id generic type instead of NSObject.

As @mike-weller said, the best way is:

 if(string == [NSNull null]){
     return @"none"
 }

'cause NSNull uses the Singleton pattern.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top