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

查看:78
本文介绍了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实际上都等于零,因此实际上它们是可以互换的.但是您是对的,为了保持一致性,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,则可以像这样检查空值:

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天全站免登陆