在NSArray中访问NSDictionary

Nas*_*ash 7 iphone objective-c nsdictionary nsarray

我有一个NSArrayNSDictionary.数组中的每个字典都有三个键:'Name','Sex'和'Age'

我如何才能找到索引NSArrayNSDictionary地方,例如,Name = 'Roger'

Ste*_*ntz 15

在iOS 4.0及更高版本中,您可以执行以下操作:

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

优雅,不是吗?


Tob*_*ias 6

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