Skip to content

Instantly share code, notes, and snippets.

@apradanas
Last active October 5, 2015 07:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save apradanas/b68ccf066966d8d0ebfe to your computer and use it in GitHub Desktop.
Save apradanas/b68ccf066966d8d0ebfe to your computer and use it in GitHub Desktop.
Replace null (NSNull) with empty string in object

If you are dealing with an unstable API, you may want to iterate through all the keys to check for null. This will prevent crash when saving the object as well.

+ (id)replaceNullWithEmptyStringForObject:(id)object {
    if ([object isKindOfClass:[NSArray class]]) {
        NSMutableArray *mutableArray = [object mutableCopy];
        [mutableArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            [mutableArray setObject:[self replaceNullWithEmptyStringForObject:obj] atIndexedSubscript:idx];
        }];
        
        return mutableArray;
    } else {
        NSMutableDictionary *mutableDictionary = [object mutableCopy];
        [mutableDictionary enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
            if ([value isKindOfClass: [NSMutableDictionary class]]) {
                [self replaceNullWithEmptyStringForObject:value];
            } else if ([value isKindOfClass:[NSArray class]]) {
                [mutableDictionary setObject:[self replaceNullWithEmptyStringForObject:value] forKey:key];
            } else if ([value isKindOfClass:[NSNull class]]) {
                [mutableDictionary setValue:@"" forKey:key];
            }
        }];
        
        return mutableDictionary;
    }
}
@jukiginanjar
Copy link

Tested:

#import "NSObject+Utils.h"

@implementation NSObject (Utils)

- (id)eliminatedNull {
    if ([self isKindOfClass:[NSArray class]]) {
        NSMutableArray *mutableArray = [NSMutableArray new];
        [self.mutableCopy enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            [mutableArray setObject:[obj eliminatedNull] atIndexedSubscript:idx];
        }];

        return mutableArray;
    } else if ([self isKindOfClass:[NSDictionary class]]) {
        NSMutableDictionary *mutableDictionary = [NSMutableDictionary new];
        [self.mutableCopy enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
            [mutableDictionary setObject:[value eliminatedNull] forKey:key];
        }];

        return mutableDictionary;
    } else {
        id result;
        if ([self isKindOfClass:[NSNull class]]) {
            result = @"";
        } else {
            result = self;
        }
        return result;
    }
}
@end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment