Skip to content

Instantly share code, notes, and snippets.

@commanda
Created July 27, 2016 15:51
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 commanda/94d7a4a6539ee6a7cf1644551b97d9d3 to your computer and use it in GitHub Desktop.
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)
+ (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