Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
This code helps you find strings nested into hierarchies of NSDictionary and NSArray
// Usage:
// NSString *toFind = @"theString";
// NSString *result = [self findStringInDictionary:dict searchString:toFind];
-(NSString *)findStringInDictionary:(NSMutableDictionary *)dict searchString:(NSString *)searchString {
NSString __block *toReturn = nil;
[dict enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
if ([obj isKindOfClass:[NSString class]]) {
if ([obj rangeOfString:searchString].location == 0) {
toReturn = key;
*stop = YES;
}
} else if ([obj isKindOfClass:[NSArray class]]) {
toReturn = [self findStringInArray:obj searchString:searchString];
if (toReturn != nil) { *stop = YES; }
} else if ([obj isKindOfClass:[NSDictionary class]]) {
toReturn = [self findStringInDictionary:obj searchString:searchString];
if (toReturn != nil) { *stop = YES; }
}
}];
return toReturn;
}
-(NSString *)findStringInArray:(NSMutableArray *)array searchString:(NSString *)searchString {
NSString __block *toReturn = nil;
[array enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
if ([obj isKindOfClass:[NSString class]]) {
if ([obj rangeOfString:searchString].location == 0) {
toReturn = obj;
*stop = YES;
}
} else if ([obj isKindOfClass:[NSArray class]]) {
toReturn = [self findStringInArray:obj searchString:searchString];
if (toReturn != nil) { *stop = YES; }
} else if ([obj isKindOfClass:[NSDictionary class]]) {
toReturn = [self findStringInDictionary:obj searchString:searchString];
if (toReturn != nil) { *stop = YES; }
}
}];
return toReturn;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.