Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
797 views
in Technique[技术] by (71.8m points)

sqlite - iPhone CoreData join

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...