mondousage mondousage -5 years ago 364
Objective-C Question

Check if NSDictionary is Null?

I've tried multiple ways. I know the dictionary is NULL, as the console also prints out when I break there. Yet when I put it in an if( ) it doesn't trigger.

([myDict count] == 0) //results in crash
(myDict == NULL)
[myDict isEqual:[NSNull null]]

Answer Source

It looks like you have a dangling or wild pointer.

You can consider Objective-C objects as pointers to structs.

You can then of course compare them with NULL, or with other pointers.


( myDict == NULL )


( myDict == [ NSNull null ] )

are both valid.

The first one will check if the pointer is NULL. NULL is usually defined as a void * with a value of 0.
Note that, for Objective-C objects, we usually use nil. nil is also defined as a void * with a value of 0, so it equals NULL. It's just here to denote a NULL pointer to an object, rather than a standard pointer.

The second one compares the address of myDict with the singleton instance of the NSNull class. So you are here comparing two pointers values.

So to quickly resume:

NULL == nil == Nil == 0

And as [ NSNull null ] is a valid instance:

NULL != [ NSNull null ]

Now about this:

( [ myDict count ] == 0 )

It may crash if you have a wild pointer:

NSDictionary * myDict;

[ myDict count ];

Unless using ARC, it will surely crash, because the myDict variable has not been initialised, and may actually point to anything.

It may also crash if you have a dangling pointer:

NSDictionary * myDict;

myDict = [ [ NSDictionary alloc ] init ];

[ myDict release ];
[ myDict count ];

Then you'll try to send a message to a deallocated object.
Sending a message to nil/NULL is always valid in Objective-C.

So it depends if you want to check if a dictionary is nil, or if it doesn't have values (as a valid dictionary instance may be empty).

In the first case, compare with nil. Otherwise, checks if count is 0, and ensure you're instance is still valid. Maybe you just forgot a retain somewhere.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download