16

我尝试了多种方法。我知道字典是 NULL,因为当我在那里休息时控制台也会打印出来。然而,当我把它放在 if( ) 中时,它不会触发。

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

5 回答 5

37

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.

So:

( myDict == NULL )

and

( 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.

于 2012-12-19T20:28:54.640 回答
8
if (TheDict == (NSDictionary*) [NSNull null]){

//TheDict is null
    }
else{
//TheDict is not null

}
于 2014-01-13T11:11:46.363 回答
0

要检查字典是否有 nil 或 NULL 数据,您可以检查 [dictionary count] 将在所有情况下返回 0

于 2014-06-05T11:48:51.787 回答
0

以上所有对我都不起作用,但是这个

if([mydict isKindOfClass:[NSNull class]])
{
   NSLog("Dic is Null")
}
else
{
   NSLog("Dic is Not Null")  
}

为我工作

于 2015-08-27T11:32:57.260 回答
0
if([NSNull null] != [serverResponseObject objectForKey:@"Your_Key"])
{
//Success
}
于 2018-08-10T13:36:23.837 回答