我很好奇,由于 json-framework 的帮助,我目前有一个 NSDictionary
,其中一些值被设置为 NSNull
对象。
目的是去除所有 NSNull
值并用空字符串替换它。
我确定有人在某处这样做过?毫无疑问,它可能是一个四线,而且很简单,我实在是太累了,无法自己解决这个问题。
最佳答案
我对 Jacob 的原始答案进行了一些更改,以将其扩展为处理存储在原始字典中的字典和数组。
#import "NSDictionary+NullReplacement.h"
#import "NSArray+NullReplacement.h"
@implementation NSDictionary (NullReplacement)
- (NSDictionary *)dictionaryByReplacingNullsWithBlanks {
const NSMutableDictionary *replaced = [self mutableCopy];
const id nul = [NSNull null];
const NSString *blank = @"";
for (NSString *key in self) {
id object = [self objectForKey:key];
if (object == nul) [replaced setObject:blank forKey:key];
else if ([object isKindOfClass:[NSDictionary class]]) [replaced setObject:[object dictionaryByReplacingNullsWithBlanks] forKey:key];
else if ([object isKindOfClass:[NSArray class]]) [replaced setObject:[object arrayByReplacingNullsWithBlanks] forKey:key];
}
return [NSDictionary dictionaryWithDictionary:[replaced copy]];
}
@end
当然还有一个数组类别:
#import "NSArray+NullReplacement.h"
#import "NSDictionary+NullReplacement.h"
@implementation NSArray (NullReplacement)
- (NSArray *)arrayByReplacingNullsWithBlanks {
NSMutableArray *replaced = [self mutableCopy];
const id nul = [NSNull null];
const NSString *blank = @"";
for (int idx = 0; idx < [replaced count]; idx++) {
id object = [replaced objectAtIndex:idx];
if (object == nul) [replaced replaceObjectAtIndex:idx withObject:blank];
else if ([object isKindOfClass:[NSDictionary class]]) [replaced replaceObjectAtIndex:idx withObject:[object dictionaryByReplacingNullsWithBlanks]];
else if ([object isKindOfClass:[NSArray class]]) [replaced replaceObjectAtIndex:idx withObject:[object arrayByReplacingNullsWithBlanks]];
}
return [replaced copy];
}
@end
有了这个,您可以使用任何数组或字典并递归地清除所有 [NSNull null] 实例。
附言为了完成起见,这里是头文件:
@interface NSDictionary (NullReplacement)
- (NSDictionary *)dictionaryByReplacingNullsWithBlanks;
@end
和数组头:
@interface NSArray (NullReplacement)
- (NSArray *)arrayByReplacingNullsWithBlanks;
@end
关于objective-c - 替换 NSDictionary 中的所有 NSNull 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8075147/