Search code examples
iosobjective-cuiviewnsarraytime-complexity

Check if NSArray contains object with specific property


I have an array of UIView. I want to check if that array contains UIView with specific tag. If it does then I should get that view or else I should receive nil.

As of now I using following

// 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]; 

This works fine but complexity is n^2. I was wondering if there is any other better way to do it.

Thanks.


Solution

  • I don't think the complexity of your method is O(n^2), it is more probably like O(n). But there is no reason to create a temporary array if you just search for a specific element. As @Josh said, you can do a simple enumeration.

    If you want to be a bit more fancy, you can write it as

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