Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/106.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios iPhone从键中的值获取数组的索引_Ios_Objective C_Arrays - Fatal编程技术网

Ios iPhone从键中的值获取数组的索引

Ios iPhone从键中的值获取数组的索引,ios,objective-c,arrays,Ios,Objective C,Arrays,我有下一个NSMutableArray: Product[0] { name => val1, Price => pricevalue 1 } Product[1] { name => val2, Price => pricevalue2 } 我想搜索:name=val2,并返回产品的索引,所以是1 __block NSUInteger index = NSUIntegerMax; [products enumerateObjec

我有下一个
NSMutableArray

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

Product[1] {
    name => val2, 
    Price => pricevalue2
}
我想搜索:
name
=
val2
,并返回产品的索引,所以是1

__block NSUInteger index = NSUIntegerMax;

[products enumerateObjectsUsingBlock: ^ (Product* product, NSUInteger idx, BOOL* stop) {
    if([product.name isEqualToString:@"val2"])
    {
        index = idx;
        *stop = YES;
    }
}];
编辑:拉文德拉的解决方案更加优雅

像这样使用

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

快乐编码………

有一些方法需要更少的代码行,但没有任何方法比直接循环更有效,您可以轻松地自己编码。如果你能自己用简单、直接的循环和if语句,相当有效地完成某件事,就没有必要寻找“聪明”的方法。