在给定值的字典数组中查找元素

lol*_*lol 1 objective-c ios

我有两个NSArray变量,每个变量都在里面得到一个类似的NSDictionary.

对于给定的行(indexPath.row):

 NSArray* array1 = ...;
 NSDictionary* item = [array1 objectAtIndex:indexPath.row];
 int myid = [[item valueForKey:@"id"] intValue];
 // id = 5
Run Code Online (Sandbox Code Playgroud)

现在我需要在array2中找到id = 5的元素,但因为我是ac #developer,我认为使用for来做这件事有点奇怪.

是否有替代品?

Mar*_*n R 6

NSArray有一个方法indexOfObjectPassingTest,你可以使用:

NSArray *array2 = ...;
int searchId = ...;
NSUInteger index2 = [array2 indexOfObjectPassingTest:^BOOL(NSDictionary *item, NSUInteger idx, BOOL *stop) {
    BOOL found = [[item objectForKey:@"id"] intValue] == searchId;
    return found;
}];

if (index2 != NSNotFound) {
    // First matching item at index2.
} else {
    // No matching item found.
}
Run Code Online (Sandbox Code Playgroud)

这将返回第一个匹配的索引.如果您需要所有匹配的索引,请使用indexesOfObjectsPassingTest.