Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSArray of many NSDictionary. What is the best way to find a NSDictionary with necessary value for given key?

Now I'm trying the following and it works.


    - (void)findDictionaryWithValueForKey:(NSString *)name {

         for (NSDictionary * set in myArray) {

            if ([[set objectForKey:@"title"] isEqualToString:name]) 
               \\do something

         }

    }

EDIT: I've added one extra argument to the post of bshirley. Now it looks more flexible.



- (NSDictionary *)findDictionaryWithValue:(NSString*)name forKey:(NSString *)key {

    __block BOOL found = NO;
    __block NSDictionary *dict = nil;

    [self.cardSetsArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        dict = (NSDictionary *)obj;
        NSString *title = [dict valueForKey:key];
        if ([title isEqualToString:name]) {
            found = YES;
            *stop = YES;
        }
    }];

    if (found) {
        return dict;
    } else {
        return nil;
    }

}
like image 524
Michael Avatar asked Jul 08 '11 12:07

Michael


1 Answers

Here's one possible implementation using newer API. (I also modified the method to actually return the value). Provided mostly to demonstrate that API. The assumption is that the title is unique to one dictionary within your array.

- (NSDictionary *)findDictionaryWithValueForKey:(NSString *)name {
  // ivar: NSArray *myArray;
  __block BOOL found = NO;
  __block NSDictionary *dict = nil;

  [myArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    dict = (NSDictionary *)obj;
    NSString *title = [dict valueForKey:@"title"];
    if ([title isEqualToString:name]) {
      found = YES;
      *stop = YES;
    }
  }];

  if (found) {
    return dict;
  } else {
    return nil;
  }

}
like image 149
bshirley Avatar answered Sep 17 '22 23:09

bshirley