Search code examples
objective-cnsstringnsdictionaryjson-frameworknsnull

Replace all NSNull objects in an NSDictionary


I'm curious, I currently have an NSDictionary where some values are set to an NSNull object thanks to the help of json-framework.

The aim is to strip all NSNull values and replace it with an empty string.

I'm sure someone has done this somewhere? No doubt it is probably a four liner and is simple, I am just far too burnt out to figure this out on my own.


Solution

  • Really simple:

    @interface NSDictionary (JRAdditions)
    - (NSDictionary *)dictionaryByReplacingNullsWithStrings;
    @end
    
    @implementation NSDictionary (JRAdditions)
    
    - (NSDictionary *)dictionaryByReplacingNullsWithStrings {
       const NSMutableDictionary *replaced = [self mutableCopy];
       const id nul = [NSNull null];
       const NSString *blank = @"";
    
       for(NSString *key in self) {
          const id object = [self objectForKey:key];
          if(object == nul) {
             //pointer comparison is way faster than -isKindOfClass:
             //since [NSNull null] is a singleton, they'll all point to the same
             //location in memory.
             [replaced setObject:blank 
                          forKey:key];
          }
       }
    
       return [replaced copy];
    }
    
    @end
    

    Usage:

    NSDictionary *someDictThatHasNulls = ...;
    NSDictionary *replacedDict = [someDictThatHasNulls dictionaryByReplacingNullsWithStrings];