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!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With