Created
July 27, 2016 15:51
-
-
Save commanda/94d7a4a6539ee6a7cf1644551b97d9d3 to your computer and use it in GitHub Desktop.
traverse a json-ish structure in objective-c (and delete certain elements from it)
This file contains 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
+ (BOOL)traverse:(NSObject *)obj comparisonBlock:(BOOL (^)(NSString *, NSObject *))comparisonBlock; | |
{ | |
if([obj isKindOfClass:[NSMutableArray class]]) | |
{ | |
NSMutableArray *array = (NSMutableArray *)obj; | |
NSMutableArray *toDelete = [@[] mutableCopy]; | |
for(NSObject *element in array) | |
{ | |
if([self _isContainer:element]) | |
{ | |
if([self traverse:element comparisonBlock:comparisonBlock]) | |
{ | |
[toDelete addObject:element]; | |
} | |
} | |
} | |
[array removeObjectsInArray:toDelete]; | |
} | |
else if([obj isKindOfClass:[NSMutableDictionary class]]) | |
{ | |
NSMutableDictionary *dict = (NSMutableDictionary *)obj; | |
NSMutableArray *keysToDelete = [@[] mutableCopy]; | |
for(NSString *subKey in [dict allKeys]) | |
{ | |
if([self _isContainer:dict[subKey]]) | |
{ | |
if([self traverse:dict[subKey] comparisonBlock:comparisonBlock]) | |
{ | |
[keysToDelete addObject:subKey]; | |
} | |
} | |
else | |
{ | |
// Leaf | |
if(comparisonBlock(subKey, dict[subKey])) | |
{ | |
return YES; | |
} | |
} | |
} | |
[dict removeObjectsForKeys:keysToDelete]; | |
} | |
return NO; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment