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).
The above mentioned answers does not cater the situation if you have array in your dictionary. Check this out
A small modification to the method can make it recursive:
Note that the fast-enumeration is now on
self
instead ofreplaced
With the code above, this example:
renders this result:
It works for me, I used nested looping to replace all NULL with nil in the entire dictionary including NSArray.
Following method works perfectly for any number of nested arrray of dictionary:
I used above modified method as per my required functionality:
// Call Method NSMutableDictionary *sortedDict = [[NSMutableDictionary alloc] init];
for (NSString *key in jobList){ NSMutableArray *tempArray = [[NSMutableArray alloc] init];
try this:
This code
Monkey patches NSDictionary - which means you can call dictionaryByReplacing... On not just the root but any nested dictionaries as you please.
I dont really agree with this from a design standpoint but it does solve your problem.