Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'?

like image 766
Nash Avatar asked Feb 27 '11 18:02

Nash


2 Answers

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?

like image 192
Stefan Arentz Avatar answered Nov 14 '22 10:11

Stefan Arentz


    NSUInteger count = [array count];
    for (NSUInteger index = 0; index < count; index++)
    {  
        if ([[[array objectAtIndex: index] objectForKey: @"Name"] isEqualToString: @"Roger"])
        {  
            return index;
        }   
    }
    return NSNotFound;
like image 6
Tobias Avatar answered Nov 14 '22 11:11

Tobias