views:

1224

answers:

2

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!

+7  A: 

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.

Martin Cote
Thanks. So (NSNull*)controller is casting controller to NSNull? I thought for that there is a isKindOfClass operator or something like that.
Thanks
Doing a pointer comparison is quicker (runtime-wise) than calling isKindOfClass, but that should work, as would doing [controller isEqual:[NSNull null]].If you had declared controller to be `id`, you wouldn't even need the cast to avoid a compiler warning.
Daniel Dickison
A: 

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.

Rose Perrone