7

I have the following code in a loop

   NSArray * images = [definitionDict objectForKey:@"Images"];
    NSLog(@"images in definitionDict %@", images);
    if (!images )
        NSLog(@"NULL");
    else
        NSLog(@"NOTNULL");

which gives the following outputs

images in definitionDict (
    "/some/brol/brol.jpg"
)
NOTNULL
images in definitionDict <null>
NOTNULL

I do not understand the second case, where the images array is null. Why is this not detected correctly in my test ? How can I debug such a problem ?

2 Answers 2

19

<null> is not nil. nil will print (null) when printed. What you have is an NSNull. NSNull IS an object, it just doesn't respond to much. Its available as a placeholder for you to use.

To test for NSNull you can use if ([images isEqual:[NSNull null]])

See the docs for more info on NSNull

Sign up to request clarification or add additional context in comments.

Comments

1

If you want to print out the memory address of an Objective-C object, or any other pointer, you should use the flag %p not %@. The flag %@, expects a string.

However if the argument isn't a string, NSLog will automatically call -description on the passed object. And when the method returns an NSNullobject, the -descriptionon that object returns the string <null>

NSObject *o = nil;
NSLog(@"%p", o);

Output: 0x00000000

NSObject *o = [[NSObject alloc] init];
NSLog(@"%p", o);
[o release];

Output: something like 0x12345678

Mind:

NSNull *n = [NSNull null];
NSLog(@"%p", n);

Output: a memory address that always will be the same, but will differ from 0x00000000

The correct way to test if their are objects in the array is like this.

NSArray *myArray = [someObject array];
if([myArray isEqual:[NSNull null]]) {
    NSLog(@"No objects");
} else {
    NSLog(@"%d objects.", (int)[myArray length];
}

3 Comments

Your solution at the bottom will crash in this situation. This isn't an array that contains no objects. It's an NSNull, and NSNull doesn't respond to length.
@JoshuaWeinberg I edited it. It still seems like a mystery why Apple created an NSNull class. And especially why would one set an NSNull object in an NSDictionary. If you just wouldn't define the key, then the method would still return nil.
In this case, you need to be able to distinguish having no object, verses having a null object. nil is just zero, it is also returning if the key doesn't exist. So here, I'd imagine after parsing some JSON into a dictionary which had a JSON null in it, an NSNull was created.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.