我如何知道 Objective C 中 NSDictionary 的 objectForKey 方法的返回值为零意味着什么?
NSDictionary 的文档说,如果 NSDictionary 不包含您的密钥,则方法 objectForKey
返回 nil
;但是,nil 不等于零吗?如果是这样,我如何知道返回值是否意味着字典包含映射到零的键,或者该键是否不存在?
The documentation for NSDictionary says that the method objectForKey
returns nil
if the NSDictionary does not contain your key; however, isn't nil the same as zero? If so, how do I know if the return value means that the dictionary contains the key mapped to zero or if that key is just non-existant?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
NSDictionaries(事实上,所有 Cocoa 集合对象)只能包含 Objective-C 对象,而不是像
int
这样的 C 原语。因此,如果您将0
存储在字典中,您会这样做:因此,检索它会像这样:
将 C 原语“包装”在对象中以存储的概念它在一个集合中,然后在另一端“展开”它,这在 Cocoa 中很常见。 (如果您尝试使用非数字值,您也可以查看
NSValue
。)NSDictionaries (and, indeed, all Cocoa collection objects) can only contain Objective-C objects, not C primitives like
int
. Therefore, were you to store0
in a dictionary, you'd do it like this:and therefore, retrieving it would go like this:
This concept of 'wrapping' a C primitive in an object to store it in a collection, then 'unwrapping' it on the other end is very common in Cocoa. (You might also look into
NSValue
if you're trying to work with non-number values.)已编辑:虽然内存中的
NULL
和nil
指向的方向恰好是0x0
并且它一直是并且可能总是如此,您不能将该值用于其他目的,只能在内存中定义未定义的地址。在NULL
的情况下,它意味着一个未定义的指针。nil
表示未定义的对象指针。这些#define
背后的想法是,程序员和程序有一个严格的标准来了解和传达内存中未定义的地址,并且在新的编译器中它可能会更改为0x42
或标准,什么都不会发生。因此,不要将nil
或NULL
视为 0;是的,确实如此,但这只是一个意外。这不是一个功能。nil
与 0 不同。nil
是对象指针,0 是数值Edited: Although the direction in memory
NULL
andnil
point to happen to be0x0
and it has always been and it may always be, you can't use that value for other purposes but to define an undefined address in memory. In the case ofNULL
it means an undefined pointer.nil
means an undefined object pointer. The idea behind these#define
s is that there's a rigid standard for programmers and programs to know and communicate undefined addresses in memory, and it could change to0x42
in a new compiler or standard and NOTHING should happen. So, don't thinknil
orNULL
as 0; yes they are, but that's a mere accident. It's not a feature.nil
is not the same as 0.nil
is an object pointer, 0 is a numeric value