core-datafilterfetchpredicatenscompoundpredicate

how to create compoundpredicate within nsFetchRequest that filters by two parameters of different entity


Some background info on my datamodel:

manufacturer <-->> item <<-->> tag

I currently generate a list of items by a fetchrequest:

- (NSFetchRequest*) rankingRequestForItem:(Item*)item {
    NSFetchRequest* r = [NSFetchRequest fetchRequestWithEntityName:@"Item"];
    NSPredicate* p = [NSPredicate predicateWithFormat:@"SELF != %@",item.objectID];
    r.resultType = NSDictionaryResultType;
r.resultType = NSDictionaryResultType;

    r.propertiesToFetch = @[[self objectIDExpressionDescription],@"itemName",
                            [self rankingExpressionDescriptionForTags:[item mutableSetValueForKey:@"itemToTag"]]];

    r.predicate = p;
    r.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"itemName" ascending:YES]];

    return r;
}

This generates a list of all items. I want to filter it for items that have a relationship to a specific manufacturer. So I'm adding a predicate after the listing of all items and it sorts by selectedManufacturer.

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"itemToMa = %@", selectedManufacturer];

This works, but is grabbing a lot of items that will be filtered out. With large data sets I'm assuming will become slower and slower as it searches all items rather than just the ones associated with one manufacturer. I want to filter for items within the initial 'rankingRequestForItem' method.

Is it possible to move the above predicate with the top predicate and create a compoundpredicate?


Solution

  • I would not worry about performance. Core Data manages that pretty well under the hood. Sometimes the order of the predicates matters, so maybe put the manufacturer filter first.

    You can combine the predicates in one as suggested in the comment to your question, or use compound predicates -- the result is pretty much the same.