I have an array of categories, and another array of category IDs. I want to pull out the categories with matching IDs. At the moment, my code looks a bit like this:
- (NSArray *)categoriesFromArray:(NSArray *)categories withIDs:(NSArray *)categoryIDs {
NSMutableArray *categoriesWithIDs = [NSMutableArray array];
for (SGBCategory *category in categories) {
for (NSNumber *categoryID in categoryIDs) {
if ([category.categoryID isEqual:categoryID]) {
[categoriesWithIDs addObject:category];
break;
}
}
}
return categoriesWithIDs;
}
Ewww, I know. So what I’d like to do is something like SELECT * FROM categories WHERE categories.categoryID in (categoryIDs) does in SQL. I think NSPredicate is the objective-c way of expressing that sort of thing, but I don’t know how to get it to do what I want. How can I speed up my array search with an NSPredicate?
I don’t know that it will be any faster, though. It basically has to do the same sort of thing as your code, plus build a predicate.
You can improve your code by making an
NSSetfrom thecategoryIDsand using-containsObject:instead of looping over thecategoryIDsand calling-isEqual:manually.