替换 NSDictionary 中的所有 NSNull 对象
我很好奇,我目前有一个 NSDictionary
,在 json-framework 的帮助下,其中一些值被设置为 NSNull
对象。
目的是删除所有 NSNull
值并将其替换为空字符串。
我确信有人在某处做过这件事?毫无疑问,这可能是一个四衬里,而且很简单,我只是太累了,无法自己解决这个问题。
I'm curious, I currently have an NSDictionary
where some values are set to an NSNull
object thanks to the help of json-framework.
The aim is to strip all NSNull
values and replace it with an empty string.
I'm sure someone has done this somewhere? No doubt it is probably a four liner and is simple, I am just far too burnt out to figure this out on my own.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
这是我的解决方案:
Here is my solution:
nsnull 上返回 nil 的类别似乎也有意义,至少对我来说。那里有一些。让所有调用都返回 nil,这似乎是有道理的。抱歉没有链接。我想如果您稍后需要使用 nspropertylistserialization,该类别可能不适合您。
A category on nsnull that returns nil seems to also sense, at least to me. There are a few out there. One makes all calls return nil which seems to make sense. Sorry no link. I guess if you need to later use nspropertylistserialization the category might not work for you.
我对 Jacob 的原始答案进行了一些更改,以将其扩展为处理存储在原始字典中的字典和数组。
当然还有一个数组类别:
有了这个,您可以采用任何数组或字典并递归地清除所有 [NSNull null] 实例。
PS 为了完整起见,这里是头文件:
和数组头:
I've made a few changes to Jacob's original answer to extend it to handle dictionaries and arrays stored within the original dictionary.
And there's also an array category of course:
With this, you can take any array or dictionary and recursively wipe out all the [NSNull null] instances.
P.S. For completion's sake, here are the header files:
And the array header:
非常简单:
用法:
Really simple:
Usage:
滚动字典寻找 NSNull 是解决这个问题的一种方法,但我采取了一种稍微懒惰的方法。您可以指定一个空字符串来代替 nil,但原理是相同的。
CPJSONDictionary.h
CPJSONDictionary.m
Rolling through the dictionary hunting for NSNull is one way to tackle the problem, but I took a slightly lazier approach. Instead of nil you could assign an empty string, but the principle is the same.
CPJSONDictionary.h
CPJSONDictionary.m
我已经测试了 Stakenborg 解决方案。它运行良好,但存在以下问题。例如,如果某个对象预计为数字,则将其转换为 NSNull 可能会导致错误。
我创建了一个新方法来直接删除
NSNull
条目。这样你只需要检查对应的密钥是否存在。添加在
NSDictionary+NullReplacement
和
NSArray+NullReplacement
中I have tested Stakenborg solution. It works well, but it has following problem. If some object is expected to be number, for instance, converting it to
NSNull
can be a source of error.I have create a new method to directly remove the
NSNull
entries. This way you only have to check that correspondant key exists.Add in
NSDictionary+NullReplacement
And in
NSArray+NullReplacement
另一种变体:
结果与 Jacob 的结果相同,并且看起来与 Jacob 的几乎相同,但在我所做的测试中,速度和内存要求是二分之一到三分之一(ARC 或 MRC)。当然,您也可以将其用作类别方法。
another variation:
The result is the same as, and it appears pretty much identical to Jacob's, but the speed and memory requirements are one half to one third (ARC or MRC) in the tests I made. Of course, you could also use it as a category method as well.