Reputation: 1910
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 ?
Upvotes: 7
Views: 8823
Reputation: 3054
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 NSNull
object, the -description
on 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];
}
Upvotes: 1
Reputation: 28688
<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
Upvotes: 19