iPhone CoreData join

2020-02-11 08:03发布

this is my core data model:

enter image description here

I'm trying to get all LanguageEntries from a database for a given category.categoryName and languageset.languageSetName e.g.

NSFetchRequest* fetchRequest = [[NSFetchRequest alloc] init];

    NSEntityDescription *entity = [NSEntityDescription entityForName:@"LanguageEntry" inManagedObjectContext:del.managedObjectContext];
    [fetchRequest setEntity:entity];

NSString* predicateString = [NSString stringWithFormat:@"Category.categoryName = %@ AND LanguageSet.languageSetName = %@", 
                        @"Food", @"English####Spanish"];

fetchRequest.predicate = [NSPredicate predicateWithFormat:predicateString];

NSError *error = nil;
NSArray* objects = [del.managedObjectContext executeFetchRequest:fetchRequest error:&error];

This always returns 0 objects. If I set the predicate string to match on one relationship (e.g. Category.categoryName = Food or languageSet.languageSetName = English####Spanish) it will return data.

This is baffling, can anyone shed some light?

->Ken

2条回答
够拽才男人
2楼-- · 2020-02-11 08:34

Your can't think of Core Data as SQL. There is no such thing as a "join" in Core Data. In this case, your trying to find the intersection of two sets of objects. Close to a join logically but not in the implementation details. And the programming devil is always in the details.

Try using the logical equal "==" like so:

@"Category.categoryName == %@ AND LanguageSet.languageSetName == %@"

I believe that will solve your problem.

The data model has a predicate editor hidden way in it. It can help you set up predicates even if you don't embed them in fetches in model itself. Just select an entity, in your case "LanguageEntity", then add a Fetch Request. The edit predicate will appear and you can use the dialog to create the predicate. It will display a textual version of the predicate that you can copy into your code.

查看更多
三岁会撩人
3楼-- · 2020-02-11 08:43

The predicate properly wasn't created correctly, you must pass the parameters to predicateWithFormat. It should have been:

fetchRequest.predicate = [NSPredicate predicateWithFormat:@"Category.categoryName = %@ AND LanguageSet.languageSetName = %@", 
                                                          @"Food", 
                                                          @"English####Spanish"];

In case you were wondering what that does is it puts quotes around the string parameters automatically which are required when using a string in a predicate. When you created the query using NSString's format method that did not put the required quotes in.

查看更多
登录 后发表回答