问题
I have to Entity in core data:
GAMES and PLAYERS
GAMES - look like this (simplified): board userid
PLAYERS userid name
PLAYERS is unique
I need to select GAMES and add the PLAYERS.name column to this result.
I have set up all core data and relationships, and can select from the "tables" and put it in a array and in a Tableview.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"GAMES" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
GamesARRAY =[context executeFetchRequest:fetchRequest error:&error];
and so on....
But HOW do i select, or access the data from players table? I know all the basics and theory, but I really need code examples. Not just answers like: use NSSet or like that..
回答1:
CoreData is not a database.
Let me repeat that again.
CoreData is not a database.
Don't think of it like one.
CoreData is a object relationship graph management and persistence framework.
If you want to access players from a given game, why are you using a userid
field in both entities? You should just use a CoreData relationship instead. That way you don't even have to think about it, you just access the relationship property on your game and you get back your player, and vice versa.
You should also rename your entity. GAMES and PLAYERS might make sense as table names, but you're not going to want to have a GAMES*
object lying around in your code that represents one game. Why not just name them Game
and Player
?
回答2:
Do you actually have a relationship on GAMES
that knows a PLAYERS
entity? If so, for any GAMES
object you can traverse that relationship (game.player
) to get the properties of a game's player object. We don't do JOINs as such in Core Data; Core Data uses relationships to abstract away things like foreign keys and JOINs (even though these are done behind the scenes in the SQLite backend, for example).
Also, as Kevin notes, GAMES
and PLAYERS
break sensible naming conventions for Core Data entities. Game
and Player
are much better.
回答3:
[[game valueForKey:@"player"] valueForKey:@"name"]
Or, if you have set up the relevant classes,
game.player.name
来源:https://stackoverflow.com/questions/13769333/ios-core-data-joining-two-tables