我如何知道 Objective C 中 NSDictionary 的 objectForKey 方法的返回值为零意味着什么?

发布于 2025-01-02 17:45:16 字数 153 浏览 0 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

属性 2025-01-09 17:45:16

NSDictionaries(事实上,所有 Cocoa 集合对象)只能包含 Objective-C 对象,而不是像 int 这样的 C 原语。因此,如果您将 0 存储在字典中,您会这样做:

[myDictionary setObject:[NSNumber numberWithInt:0] forKey:@"myKey"];

因此,检索它会像这样:

NSNumber* resultObj = [myDictionary objectForKey:@"myKey"];
if (resultObj == nil)
{
    //Key didn't exist
}
else
{
    int result = [resultObj intValue];
    //Now do your work.
}

将 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 store 0 in a dictionary, you'd do it like this:

[myDictionary setObject:[NSNumber numberWithInt:0] forKey:@"myKey"];

and therefore, retrieving it would go like this:

NSNumber* resultObj = [myDictionary objectForKey:@"myKey"];
if (resultObj == nil)
{
    //Key didn't exist
}
else
{
    int result = [resultObj intValue];
    //Now do your work.
}

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

ヤ经典坏疍 2025-01-09 17:45:16

已编辑:虽然内存中的NULLnil指向的方向恰好是0x0并且它一直是并且可能总是如此,您不能将该值用于其他目的,只能在内存中定义未定义的地址。在NULL的情况下,它意味着一个未定义的指针。 nil 表示未定义的对象指针。这些#define背后的想法是,程序员和程序有一个严格的标准来了解和传达内存中未定义的地址,并且在新的编译器中它可能会更改为0x42或标准,什么都不会发生。因此,不要将 nilNULL 视为 0;是的,确实如此,但这只是一个意外。这不是一个功能。
nil 与 0 不同。nil 是对象指针,0 是数值

Edited: Although the direction in memory NULL and nil point to happen to be 0x0 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 of NULL it means an undefined pointer. nil means an undefined object pointer. The idea behind these #defines is that there's a rigid standard for programmers and programs to know and communicate undefined addresses in memory, and it could change to 0x42 in a new compiler or standard and NOTHING should happen. So, don't think nil or NULL 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文