How to remove a null value from NSDictionary
Iterate through the dictionary and look for any null entries and remove them.
NSMutableDictionary *prunedDictionary = [NSMutableDictionary dictionary];
for (NSString * key in [yourDictionary allKeys])
{
if (![[yourDictionary objectForKey:key] isKindOfClass:[NSNull class]])
[prunedDictionary setObject:[yourDictionary objectForKey:key] forKey:key];
}
After that, prunedDictionary
should have all non-null items in the original dictionary.
Here is my category-based recursive solution for dictionaries containing dictionaries and arrays which values can also be dictionaries and arrays:
File NSDictionary+Dario.m:
#import "NSArray+Dario.h"
@implementation NSDictionary (Dario)
- (NSDictionary *) dictionaryByReplacingNullsWithEmptyStrings {
const NSMutableDictionary *replaced = [NSMutableDictionary new];
const id nul = [NSNull null];
const NSString *blank = @"";
for(NSString *key in self) {
const id object = [self objectForKey:key];
if(object == nul) {
[replaced setObject:blank forKey:key];
} else if ([object isKindOfClass:[NSDictionary class]]) {
[replaced setObject:[object dictionaryByReplacingNullsWithEmptyStrings] forKey:key];
} else if ([object isKindOfClass:[NSArray class]]) {
[replaced setObject:[object arrayByReplacingNullsWithEmptyStrings] forKey:key];
} else {
[replaced setObject:object forKey:key];
}
}
return [NSDictionary dictionaryWithDictionary:(NSDictionary*)replaced];
}
@end
File NSArray+Dario.m:
#import "NSDictionary+Dario.h"
@implementation NSArray (Dario)
- (NSArray *) arrayByReplacingNullsWithEmptyStrings {
const NSMutableArray *replaced = [NSMutableArray new];
const id nul = [NSNull null];
const NSString *blank = @"";
for (int i=0; i<[self count]; i++) {
const id object = [self objectAtIndex:i];
if ([object isKindOfClass:[NSDictionary class]]) {
[replaced setObject:[object dictionaryByReplacingNullsWithEmptyStrings] atIndexedSubscript:i];
} else if ([object isKindOfClass:[NSArray class]]) {
[replaced setObject:[object arrayByReplacingNullsWithEmptyStrings] atIndexedSubscript:i];
} else if (object == nul){
[replaced setObject:blank atIndexedSubscript:i];
} else {
[replaced setObject:object atIndexedSubscript:i];
}
}
return [NSArray arrayWithArray:(NSArray*)replaced];
}
Use this for remove null from dictionary
- (NSMutableDictionary *)recursive:(NSMutableDictionary *)dictionary {
for (NSString *key in [dictionary allKeys]) {
id nullString = [dictionary objectForKey:key];
if ([nullString isKindOfClass:[NSDictionary class]]) {
[self recursive:(NSMutableDictionary*)nullString];
} else {
if ((NSString*)nullString == (id)[NSNull null])
[dictionary setValue:@"" forKey:key];
}
}
return dictionary;
}
Another variation, without (explicit) loop:
NSMutableDictionary *dict = [yourDictionary mutableCopy];
NSArray *keysForNullValues = [dict allKeysForObject:[NSNull null]];
[dict removeObjectsForKeys:keysForNullValues];