iPhone Get Index of an array from Value in a Key

I have the next NSMutableArray:

Product[0] {
    name => val1, 
    Price => pricevalue 1
}

Product[1] {
    name => val2, 
    Price => pricevalue2
}

I want to search for: name = val2 and return the index of product, so 1.

Upvotes: 1

Views: 391

Answers (2)

Léo Natan
Léo Natan

Reputation: 57060

__block NSUInteger index = NSUIntegerMax;

[products enumerateObjectsUsingBlock: ^ (Product* product, NSUInteger idx, BOOL* stop) {
    if([product.name isEqualToString:@"val2"])
    {
        index = idx;
        *stop = YES;
    }
}];

Edit: Ravindra's solution is more elegant!

Upvotes: 1

Ravindra Singh
Ravindra Singh

Reputation: 50

Use like this

NSIndexSet *indices = [array 
                       indexesOfObjectsPassingTest:^(id obj, NSUInteger idx, BOOL *stop) {
                       return [[obj objectForKey:@"name"] isEqualToString:@"val2"];
}];

Happy coding.........

Upvotes: 1

Related Questions