检查NSDictionary是否为空? [英] Check if NSDictionary is Null?

查看:122
本文介绍了检查NSDictionary是否为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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]]


推荐答案

看起来你有一个悬挂或狂野的指针。

It looks like you have a dangling or wild pointer.

你可以将Objective-C对象视为指向结构的指针。

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

然后你可以将它们与 NULL 或其他指针进行比较。

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

所以:

( myDict == NULL )

( myDict == [ NSNull null ] )

均有效。

第一个将检查指针是否为 NULL NULL 通常定义为 void * ,其值为0.

请注意,对于Objective-C对象,我们通常使用 nil nil 也被定义为 void * ,其值为0,因此它等于 NULL 。它只是在这里表示一个 NULL 指向对象的指针,而不是标准指针。

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.

第二个比较使用 NSNull 类的单例实例的 myDict 的地址。所以你在这里比较两个指针值。

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

所以要快速恢复:

NULL == nil == Nil == 0

以及 [NSNull null] 是一个有效的实例:

And as [ NSNull null ] is a valid instance:

NULL != [ NSNull null ]

现在关于这个:

( [ myDict count ] == 0 )

如果你有野外它可能会崩溃指针:

It may crash if you have a wild pointer:

NSDictionary * myDict;

[ myDict count ];

除非使用ARC,否则肯定会崩溃,因为 myDict 变量尚未初始化,实际上可能指向任何东西。

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 ];

然后你会尝试向解除分配的对象发送消息。

发送消息到 nil / NULL 在Objective-C中始终有效。

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

所以这取决于你是否要检查字典是否是 nil ,或者它是否没有值(因为有效的字典实例可能为空)。

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

在第一种情况下,与 nil 进行比较。否则,检查count是否为0,并确保实例仍然有效。也许你只是忘了保留某个地方。

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.

这篇关于检查NSDictionary是否为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆