How can I get NSMutableDictionary keys that start with a specific string

I have a json answer, and I need to get all the values ​​whose keys are a specific string ... for example, for example: www_name, www_age, etc. in nsmutabledictionary as keys now I want to look for all these values ​​that have "www_" as part of their string.

+3
source share
2 answers

Switch dictionary and filter.

NSMutableArray* result = [NSMutableArray array];
for (NSString* key in dictionary) {
  if ([key hasPrefix:@"www_"]) {
    [result addObject:[dictionary objectForKey:key]];
    // write to a dictionary instead of an array
    // if you want to keep the keys too.
  }
}
return result;
+21
source

Instead of iterating over the collection yourself, you can also ask the dictionary to filter the results for you and return the array using NSPredicate.

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF beginswith www_"];
NSArray *filtered = [[dictionary allKeys] filteredArrayUsingPredicate:predicate];

Just a thought.

+13
source

Source: https://habr.com/ru/post/1746964/


All Articles