0

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?

James
  • 2,483
  • 2
  • 24
  • 31
  • Why do you think you need to cast? Have you tried it without casting? – Florian Mielke Jul 24 '13 at 08:44
  • 1
    I don't think I need to, I'm asking if there is a reason someone before me thought it did need casting – James Jul 24 '13 at 08:46
  • 1
    I see this in NSNull's class @interface NSNull : NSObject so I don't think you gotta typecast before checking, because NSNull is also NSObject but not vice versa. – Satheesh Jul 24 '13 at 08:47

3 Answers3

3

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

Mike Weller
  • 45,401
  • 15
  • 131
  • 151
  • 1
    Is it feasible to use == to compare string in Objective-C ? It can give violating results .Don't you think so ? Generally == is used for numeric comparison. – βhargavḯ Jul 24 '13 at 08:51
  • But if you are comparing against `[NSNull null]` (the singleton) it will be safe. – Mike Weller Jul 24 '13 at 08:52
  • If the string is not null, the == against `[NSNull null]` will be false. – Mike Weller Jul 24 '13 at 08:54
  • Thanks, I'm going to keep `isEqual` for consistancy but I get why you could use `==` I just wanted to check that no-one could see a good reason for the cast – James Jul 24 '13 at 09:09
0

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.

Tirth
  • 7,801
  • 9
  • 55
  • 88
0

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

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

'cause NSNull uses the Singleton pattern.

oskarko
  • 3,382
  • 1
  • 26
  • 26