1

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.

1
  • There are ways to do it that require fewer lines of code, but no way more efficient than the straight-forward loop which you can easily code yourself. There's no need to look for "clever" ways to do something if you can do it yourself, reasonably efficiently, with simple, straight-forward loops and if statements. Commented Jan 2, 2014 at 12:52

2 Answers 2

1

Use like this

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

Happy coding.........

Sign up to request clarification or add additional context in comments.

Comments

1
__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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.