Skip to content

Instantly share code, notes, and snippets.

@zhugexiaobo
Created May 28, 2014 08:47
Show Gist options
  • Save zhugexiaobo/80403064e91ec8c0f460 to your computer and use it in GitHub Desktop.
Save zhugexiaobo/80403064e91ec8c0f460 to your computer and use it in GitHub Desktop.
Replace all NSNull objects in an NSDictionary
@interface NSDictionary (NullReplacement)
- (NSDictionary *)dictionaryByReplacingNullsWithBlanks;
@end
@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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment