Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 578
slonkar Avatar asked Nov 26 '13 20:11

slonkar


People also ask

How do you check if an array contains a value in Objective C?

To determine if the array contains a particular instance of an object, you can test for identity rather than equality by calling the indexOfObjectIdenticalTo: method and comparing the return value to NSNotFound .

How do I create an NSArray in Objective C?

Creating NSArray Objects Using Array Literals In addition to the provided initializers, such as initWithObjects: , you can create an NSArray object using an array literal. In Objective-C, the compiler generates code that makes an underlying call to the init(objects:count:) method.

What is swift NSArray?

NSArray is an immutable Objective C class, therefore it is a reference type in Swift and it is bridged to Array<AnyObject> . NSMutableArray is the mutable subclass of NSArray .


1 Answers

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];
}
like image 63
Martin R Avatar answered Sep 20 '22 16:09

Martin R