1

I was getting random crashes in my app until I narrowed it down to a particular method. In that method I expect an NSString as a parameter. This NSString can sometimes be nil in which case the method ends and no harm is done.

When I run my method's parameter through NSLog(@"%@", myString) I found that I get one of these:

  1. The contents of an actual NSString
  2. (null)
  3. <null>

The first two are expected and handled by my method. The third one, <null>, crashes my app with -[NSNull length]: unrecognized selector sent to instance 0x1b2ace8.

I have found a way around the problem by checking for nil or isKindOfClass, but my question is what is the difference between (null) and <null>?.

Hamed Rajabi Varamini
  • 3,439
  • 3
  • 24
  • 38
Julian
  • 8,808
  • 8
  • 51
  • 90
  • possible duplicate of [What are the differences between nil, NULL and \[NSNULL nil\]?](http://stackoverflow.com/questions/6814427/what-are-the-differences-between-nil-null-and-nsnull-nil) –  Jul 02 '12 at 03:58
  • 1
    @duskwuff: Note that neither the question nor the answers there address the two description strings, `(null)` and ``. – jscs Jul 02 '12 at 04:04
  • I've edited the accepted answer to include a note on how the two values stringify. :) –  Jul 02 '12 at 04:14

1 Answers1

5

(null) is the string that NSLog() prints when you use the format specifier %@ with a nil value. <null> is the result of sending description to the NSNull singleton (which you access via [NSNull null]).

NSNull is used as a "no object" placeholder in Cocoa collections (NSArray and NSDictionary) because they cannot contain nil.

The two description strings are confusingly similar, and one could argue that NSNull should have a bug filed against it to make this a little more clear.

jscs
  • 63,694
  • 13
  • 151
  • 195
  • Ah, I see. Thanks for clearing that up! I have to hunt the origin of that NSNull in my app then. For the life of me I've been trying for the last few hours to no avail. – Julian Jul 02 '12 at 04:03
  • 1
    Parsing JSON seems to be the most common task that causes this issue -- constructing a Cocoa collection with some missing data requires the use of `NSNull`. – jscs Jul 02 '12 at 04:06
  • And you are right one more time. I've found the culprit inside a dictionary coming from a remote JSON object. Thanks! – Julian Jul 02 '12 at 04:25