问题描述:

I have two NSArray variables, each one of then gets a similar NSDictionary inside.

For a given row (indexPath.row):

 NSArray* array1 = ...;

NSDictionary* item = [array1 objectAtIndex:indexPath.row];

int myid = [[item valueForKey:@"id"] intValue];

// id = 5

Now I need to find the element with id = 5 in array2, but because I'm a c# developer, I think it is a little weird to use a for to do that.

Is there any alternatives to a for?

网友答案:

NSArray has a method indexOfObjectPassingTest which you can use:

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.
}

This returns the first matching index. If you need all matching indexes, use indexesOfObjectsPassingTest.

相关阅读:
Top