Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's this (NSNull*)controller == [NSNull null] supposed to do? Why not just controller == nil?

In an Apple example I've seen this:

myController *controller = [viewControllers objectAtIndex:page];
if ((NSNull *)controller == [NSNull null]) {
    controller = [[myController alloc] initWithPageNumber:page];
    [viewControllers replaceObjectAtIndex:page withObject:controller];
    [controller release];
}

I am very interested in this line:

if ((NSNull *)controller == [NSNull null]) {

If I would have done that, I would have just checked for nil. Why do they do that so damn complicated? And what's that actually doing? For me it looks like they're casting the controller object to NSNull, and then check if that's the same as null from NSNull.

A.F.A.I.K. nil means "no object", and null means "nothing". Please help me to get a clear picture here!

like image 596
Thanks Avatar asked May 13 '09 21:05

Thanks


2 Answers

Most containers doesn't allow 'nil' object to be inserted in them. If you really want to insert a null value in your container, the NSNull instance can be used (NSNull is a singleton).

In your particular example, the controller is fetched from an array. It is then good practice to make sure that the object was not the NSNull instance.

like image 89
Martin Cote Avatar answered Oct 05 '22 23:10

Martin Cote


Collection classes like NSArray and NSDictionary cannot contain nil values. Your ivar, viewController, is an instance of a collection class. NSNULL was created specifically as a placeholder for nil, and you can put it into collection classes.

The NSNull class defines a singleton object, which means that there's only ever a single instance of NSNull (which you create using [NSNull null]), but it can be used in as many places as you wish.

like image 24
Rose Perrone Avatar answered Oct 05 '22 23:10

Rose Perrone