将nil添加到array(dict)时如何自动将nil转换为[NSNull null]? [英] how to auto convert nil to [NSNull null] when add it to array(dict)?

查看:69
本文介绍了将nil添加到array(dict)时如何自动将nil转换为[NSNull null]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些值需要添加到数组中(使用 initWithObjects ),并在以后编码为JSON字符串。

I have some values need to be added to an array (using initWithObjects), and encode to JSON string later.

众所周知,当数组遇到 nil 时,它将停止读取下一个值。

As everyone knows, when array meet a nil, it will stop read next value.

我应该检查每个值,然后手动将其转换为 [ NSNull null] ,然后将其添加到数组?

Should I check every value, and manually convert it to [NSNull null] before add it to array?

推荐答案


检查每个值,然后手动将其转换为[NSNull null],然后再将其添加到数组?

Should I check every value, and manually convert it to [NSNull null] before add it to array?

是。您可以创建一个简单的帮助程序方法/函数:

Yes. You can create a simple helper method/function:

id GuardJSONElement(id arg) { return arg ? arg : [NSNull null]; }

然后:

[array addObject:GuardJSONElement(something)];

这篇关于将nil添加到array(dict)时如何自动将nil转换为[NSNull null]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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