I\'m frequently finding the need to cache data structures created by NSJSONSerialization
to disk and as -writeToFile
fails if there are nulls, I ne
+ (id)getObjectWithoutNullsForObject:(id)object
{
id objectWithoutNulls;
if ([object isKindOfClass:[NSDictionary class]])
{
NSMutableDictionary *dictionary = ((NSDictionary *)object).mutableCopy;
[dictionary removeObjectsForKeys:[dictionary allKeysForObject:[NSNull null]]];
for (NSString *key in dictionary.allKeys)
{
dictionary[key] = [self getObjectWithoutNullsForObject:dictionary[key]];
}
objectWithoutNulls = dictionary;
}
else if ([object isKindOfClass:[NSArray class]])
{
NSMutableArray *array = ((NSArray *)object).mutableCopy;
[array removeObject:[NSNull null]];
for (NSUInteger index = 0; index < array.count; index++)
{
array[index] = [self getObjectWithoutNullsForObject:array[index]];
}
objectWithoutNulls = array;
}
else if ([object isKindOfClass:[NSNull class]])
{
objectWithoutNulls = Nil;
}
else
{
objectWithoutNulls = object;
}
return objectWithoutNulls;
}