替换NSDictionary中的所有NSNull对象 [英] Replace all NSNull objects in an NSDictionary
本文介绍了替换NSDictionary中的所有NSNull对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我很好奇,由于json-framework的帮助,我目前有一个NSDictionary
,其中一些值设置为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.
目标是剥离所有NSNull
值,并将其替换为空字符串.
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.
谢谢!
推荐答案
非常简单:
@interface NSDictionary (JRAdditions)
- (NSDictionary *)dictionaryByReplacingNullsWithStrings;
@end
@implementation NSDictionary (JRAdditions)
- (NSDictionary *)dictionaryByReplacingNullsWithStrings {
const NSMutableDictionary *replaced = [self mutableCopy];
const id nul = [NSNull null];
const NSString *blank = @"";
for(NSString *key in self) {
const id object = [self objectForKey:key];
if(object == nul) {
//pointer comparison is way faster than -isKindOfClass:
//since [NSNull null] is a singleton, they'll all point to the same
//location in memory.
[replaced setObject:blank
forKey:key];
}
}
return [replaced copy];
}
@end
用法:
NSDictionary *someDictThatHasNulls = ...;
NSDictionary *replacedDict = [someDictThatHasNulls dictionaryByReplacingNullsWithStrings];
这篇关于替换NSDictionary中的所有NSNull对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文