Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing for null in objective-c

Tags:

objective-c

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 ?

like image 409
madewulf Avatar asked Dec 22 '11 13:12

madewulf


People also ask

How do you check for null in Objective C?

Nil = (capitalized) is a null pointer to an Objective-C class. NULL = (all caps) is a null pointer to anything else (C pointers, that is). [NSNull null] = (singleton) for situations where use of nil is not possible (adding/receiving nil to/from NSArrays e.g.)

How do you check if a string is empty or null in Objective C?

You can check if [string length] == 0 . This will check if it's a valid but empty string (@"") as well as if it's nil, since calling length on nil will also return 0.

What is NSString?

A static, plain-text Unicode string object that bridges to String ; use NSString when you need reference semantics or other Foundation-specific behavior.


1 Answers

<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

like image 163
Joshua Weinberg Avatar answered Oct 10 '22 20:10

Joshua Weinberg