Ios 检查NSArray是否包含具有特定属性的对象
我有一个UIView数组。我想检查该数组是否包含带有特定标记的UIView。如果是这样的话,我应该得到那个视图,否则我将得到零 到目前为止,我使用以下方法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;
// 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的一样好。从我的角度来看,我会选择一个最直观的,为人类读者而不是编译器编写的。