This question is similar to this question, however this method only works on the root level of the dictionary.
I'm looking to replace any occurrence of NSNull
values with an empty string, so that I can save the full dictionary to a plist file (if i add it with the NSNull's the file won't write).
My dictionary, however, has nested dictionaries inside it. Like this:
"dictKeyName" = {
innerStrKeyName = "This is a string in a dictionary";
innerNullKeyName = "<null>";
innerDictKeyName = {
"innerDictStrKeyName" = "This is a string in a Dictionary in another Dictionary";
"innerDictNullKeyName" = "<null>";
};
};
If I use:
@interface NSDictionary (JRAdditions)
- (NSDictionary *) dictionaryByReplacingNullsWithStrings;
@end
@implementation NSDictionary (JRAdditions)
- (NSDictionary *) dictionaryByReplacingNullsWithStrings {
const NSMutableDictionary *replaced = [NSMutableDictionary dictionaryWithDictionary:self];
const id nul = [NSNull null];
const NSString *blank = @"";
for(NSString *key in replaced) {
const id object = [self objectForKey:key];
if(object == nul) {
[replaced setObject:blank forKey:key];
}
}
return [NSDictionary dictionaryWithDictionary:replaced];
}
@end
I get something like this:
"dictKeyName" = {
innerStrKeyName = "This is a string in a dictionary";
innerNullKeyName = ""; <-- this value has changed
innerDictKeyName = {
"innerDictStrKeyName" = "This is a string in a Dictionary in another Dictionary";
"innerDictNullKeyName" = "<null>"; <-- this value hasn't changed
};
};
Is there a way of finding every NSNull
value from all dictionaries including nested dictionaries...?
EDIT: The data is being drawn from a JSON feed, so the data I receive is dynamic (and I don't want to have to update the app everytime the feed changes).