Last active
August 29, 2015 14:21
-
-
Save benvium/13abb7de415d5c9cecf2 to your computer and use it in GitHub Desktop.
In-place removal of [NSNull null] values in collections.Useful when importing JSON data into realm-cocoa. Note that the whole structure must be Mutable (e.g. all child collections are NSMutableArray or NSMutableDictionary)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| @import Foundation; | |
| // In-place removal of [NSNull null] values | |
| // Useful when importing into Realm | |
| @interface NSMutableDictionary (BVMNullReplacement) | |
| - (void)bvm_removeNulls; | |
| @end | |
| // In-place removal of [NSNull null] values | |
| // Useful when importing into Realm | |
| @interface NSMutableArray (BVMNullReplacement) | |
| - (void)bvm_removeNulls; | |
| @end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #import "NSMutableDictionary+BVMNullReplacement.h" | |
| @implementation NSMutableDictionary (BVMNullReplacement) | |
| - (void)bvm_removeNulls { | |
| NSArray *keysForNullValues = [self allKeysForObject:[NSNull null]]; | |
| [self removeObjectsForKeys:keysForNullValues]; | |
| NSArray *keys = self.allKeys; | |
| for (int i = 0; i < keys.count; i++) { | |
| id key = keys[(NSUInteger) i]; | |
| if ([self[key] isKindOfClass:[NSMutableDictionary class]]) { | |
| [self[key] bvm_removeNulls]; | |
| } else if ([self[key] isKindOfClass:[NSMutableArray class]]) { | |
| [self[key] bvm_removeNulls]; | |
| } | |
| } | |
| } | |
| @end | |
| @implementation NSMutableArray (BVMNullReplacement) | |
| - (void)bvm_removeNulls { | |
| // Remove all nulls | |
| [self removeObjectIdenticalTo:[NSNull null]]; | |
| // Recurse | |
| for (NSUInteger idx = 0; idx < [self count]; idx++) { | |
| id object = self[idx]; | |
| if ([object isKindOfClass:[NSMutableDictionary class]]) { | |
| [((NSMutableDictionary *) object) bvm_removeNulls]; | |
| } else if ([object isKindOfClass:[NSMutableArray class]]) { | |
| [((NSMutableArray *) object) bvm_removeNulls]; | |
| } | |
| } | |
| } | |
| @end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment