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.
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 .
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.
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 .
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];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With