Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/104.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/4/facebook-graph-api/2.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 检查NSArray是否包含具有特定属性的对象_Ios_Objective C_Uiview_Nsarray_Time Complexity - Fatal编程技术网

Ios 检查NSArray是否包含具有特定属性的对象

Ios 检查NSArray是否包含具有特定属性的对象,ios,objective-c,uiview,nsarray,time-complexity,Ios,Objective C,Uiview,Nsarray,Time Complexity,我有一个UIView数组。我想检查该数组是否包含带有特定标记的UIView。如果是这样的话,我应该得到那个视图,否则我将得到零 到目前为止,我使用以下方法 // validCells is an array UIView NSPredicate *p = [NSPredicate predicateWithBlock:^BOOL(id obj, NSDictionary *ignored){ return ((UIView *)obj).tag == i;

我有一个UIView数组。我想检查该数组是否包含带有特定标记的UIView。如果是这样的话,我应该得到那个视图,否则我将得到零

到目前为止,我使用以下方法

// validCells is an array UIView

NSPredicate *p = [NSPredicate predicateWithBlock:^BOOL(id obj, NSDictionary *ignored){
            return ((UIView *)obj).tag == i;
        }];

UIView *cell = [[validCells filteredArrayUsingPredicate:p] lastObject]; 
这很好,但复杂性为n^2。我想知道是否还有其他更好的方法


谢谢。

我不认为你的方法的复杂性是O(n^2),它更像是O(n)。 但是,如果只搜索特定的数组,就没有理由创建临时数组 元素。正如@Josh所说,您可以进行简单的枚举

如果你想更花哨一点,你可以把它写成

NSUInteger index = [validCells indexOfObjectPassingTest:^BOOL(UIView *view, NSUInteger idx, BOOL *stop) {
    return view.tag == idx;
}];
if (index != NSNotFound) {
    cell = validCells[index];
}

您是否特别需要使用谓词?只需枚举,就可以在O(n)中完成。还有,这真的太慢了吗?你可能有多少视图?为什么复杂性是n^2?为什么你认为复杂性是O(n^2)?C.A.R.Hoare:“过早优化是编程中所有邪恶的根源。”@Sumit你的方法和Martin的一样好。从我的角度来看,我会选择一个最直观的,为人类读者而不是编译器编写的。