TouchJSON,处理 NSNull [英] TouchJSON, dealing with NSNull

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

问题描述

嗨我正在使用 TouchJSON 反序列化一些 JSON.我过去一直在使用它,在那些场合我手动处理了 NSNull 的出现.我认为作者也必须处理这个问题,所以我再这样做只会是开销.然后我在文档中找到了这个:

Hi I am using TouchJSON to deserialize some JSON. I have been using it in the past and on those occasions I dealt with occurrences of NSNull manually. I would think the author had to deal with this as well, so me doing that again would just be overhead. I then found this in the documentation:

避免输出中的 NSNull 值.

Avoiding NSNull values in output.

NSData *theJSONData = /* some JSON data */
CJSONDeserializer *theDeserializer = [CJSONDeserializer deserializer];
theDeserializer.nullObject = NULL;
NSError *theError = nil;
id theObject = [theDeserializer deserialize:theJSONData error:&theError];}

根据我的理解,类的用户可以将 C 样式的空指针传递给反序列化器,当它遇到 NSNull 时,它将插入传递给它的值 (NULL).所以稍后当我使用这些值时,我不会得到 NSNull,而是 NULL.

The way I understand it the user of the class can pass a C-style null pointer to the deserializer and when it encounters a NSNull it will insert the values (NULL) passed to it. So later on when I use the values I won't get NSNull, but NULL.

这似乎很奇怪,返回值是一个只能包含对象的 NSDictionary,该值不应该默认为 'nil' 吗?

This seems strange, the return value is an NSDictionary which can only contain Objects, shouldn't the value default to 'nil' instead?

如果它是 NULL 我可以检查这样的值吗?

if([jsonDataDict objectForKey:someKey] == NULL)

这样做似乎更合乎逻辑:

It would seem more logically to be able to do this:

if(![jsonDataDict objectForKey:someKey])

更不用说所有允许传递 nil 但传递 NULL 会导致崩溃的情况.

No to mention all the cases where passing nil is allowed but passing NULL causes a crash.

或者我可以将nil"传递给解串器吗?

这很大程度上源于我仍在为 nil、NULL、[NSNULL null] 苦苦挣扎,也许我没有看到使用 nil 的潜在警告.

Much of this stems from me still struggling with nil, NULL, [NSNULL null], maybe I am failing to see the potential caveats in using nil.

推荐答案

nilNULL 实际上都等于 0,因此在实践中它们是可以互换的.但你是对的,为了一致性,TouchJSON 的文档应该使用 theDeserializer.nullObject = nil 而不是 NULL.

nil and NULL are actually both equal to zero, so they are, in practice, interchangeable. But you're right, for consistency, the documentation for TouchJSON should have used theDeserializer.nullObject = nil instead of NULL.

现在,当您这样做时,您的第二个谓词实际上可以正常工作:

Now, when you do that, your second predicate actually works fine:

if (![jsonDataDict objectForKey:someKey])

因为当您将 nullObject 设置为 nil(或 NULL)时,TouchJSON 会省略字典中的键.当字典中不存在键时,NSDictionary 返回 nil,它为零,因此您的 if 条件按您的预期工作.

because TouchJSON omits the key from the dictionary when you have nullObject set to nil (or NULL). When the key doesn't exist in the dictionary, NSDictionary returns nil, which is zero so your if condition works as you expect.

如果你没有将 nullObject 指定为 nil,你可以像这样检查 null:

If you don't specify nullObject as nil, you can instead check for null like so:

if ([jsonDataDict objectForKey:someKey] == [NSNull null])

这篇关于TouchJSON,处理 NSNull的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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