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

slo*_*kar 3 objective-c time-complexity uiview nsarray ios

我有一个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]; 
Run Code Online (Sandbox Code Playgroud)

这很好但复杂性是n ^ 2.我想知道是否还有其他更好的办法.

谢谢.

Mar*_*n R 18

我不认为你的方法的复杂性是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];
}
Run Code Online (Sandbox Code Playgroud)