Nash
Nash

Reputation: 201

Accessing NSDictionary inside NSArray

I have an NSArray of NSDictionary. Each dictionary in the array has three keys: 'Name', 'Sex' and 'Age'

How can I find the index in NSArray of NSDictionary where, for example, Name = 'Roger'?

Upvotes: 7

Views: 7281

Answers (4)

Stefan Arentz
Stefan Arentz

Reputation: 34935

On iOS 4.0 and up you can do the following:

- (NSUInteger) indexOfObjectWithName: (NSString*) name inArray: (NSArray*) array
{
    return [array indexOfObjectPassingTest:
        ^BOOL(id dictionary, NSUInteger idx, BOOL *stop) {
            return [[dictionary objectForKey: @"Name"] isEqualToString: name];
    }];
}

Elegant, no?

Upvotes: 15

Tobias
Tobias

Reputation: 579

    NSUInteger count = [array count];
    for (NSUInteger index = 0; index < count; index++)
    {  
        if ([[[array objectAtIndex: index] objectForKey: @"Name"] isEqualToString: @"Roger"])
        {  
            return index;
        }   
    }
    return NSNotFound;

Upvotes: 6

dianovich
dianovich

Reputation: 2287

If you're using iOS > 3.0 you will be able to use the for in construct.

for(NSDictionary *dict in myArray) {
  if([[dict objectForKey:@"Name"] isEqualToString:@"Roger"]) {
    return [myArray indexForObject:dict];
  }
}

Upvotes: -1

Seva Alekseyev
Seva Alekseyev

Reputation: 61331

There's method [NSArray indexOfObjectPassingTest]. But it employs blocks, an Apple extension to C, and therefore is evil. Instead, do this:

NSArray *a; //Comes from somewhere...
int i;
for(i=0;i<a.count;i++)
    if([[[a objectAtIndex:i] objectForKey: @"Name"] compare: @"Roger"] == 0)
        return i; //That's the index you're looking for
return -1; //Not found

Upvotes: -2

Related Questions