aritchie
aritchie

Reputation: 601

Core Data Detail View from To-Many relationship

I'm struggling with some aspects of Core Data, namely setting up a UITableView to list data from a to-many relationship.

I have three entities, Teams, TeamDetails and Players:

enter image description here

In the first view, I list the names of all the teams in the Teams entity, then tapping each cell segues to an intermediate view with buttons to either edit a team's details or edit a team's players. Tapping on a button segues to another UITableView that lists the Team's details or Players.

Listing the TeamDetails works, since it is a one-to-one relationship and a static cell table.

I'm trying to set up a UITableViewController that lists all the players that are associated with the selected team. So I pass the ManagedObjectContext etc to the table view controller via the segue as shown below:

else if ([segue.identifier isEqualToString:@"ShowPlayersSegue"]){
    NSLog(@"Setting ShowPlayersTVC as a delegate of EditPlayerTVC");
    ShowPlayersTVC *showPlayerTVC = segue.destinationViewController;
    showPlayerTVC.delegate = self;
    showPlayerTVC.managedObjectContext = self.managedObjectContext;

    showPlayerTVC.team = self.team;
    showPlayerTVC.player = self.team.playerDetails;
}

So, in my showPlayerTVC I want to get the set of players for that specific team, then have a row for each one that shows the playerName attribute as the cell textlabel.text.

I've been reading tutorials and playing around for ages without getting much success. I think I need to create an array of Player objects from the NSSet, which I can do, but I can't get the UITableview to list the objects. I'm probably missing something fundamental here, but any suggestions would be appreciated.

Upvotes: 1

Views: 378

Answers (1)

Mundi
Mundi

Reputation: 80273

First, there are some issues with your data model.

The one-to-one to details I do not understand - why not just add attributes to the Team entity? Also, you may want to transform some of these into more flexible relationships, such as a Trainer entity, etc.

Also, your naming is flawed and will lead to programming errors or at least make your code difficult to read. Note the singular / plural confusion. Here is my suggestion for naming your entities / relationships:

Team - players <--------------->> team - Player  

To display data in an a table view you should use NSFetchedResultsController. Let the FRC fetch the Player entity and give its fetch request the following predicate:

[NSPredicate predicateWithFormat:@"team = %@", teamObject]; 

Your segue code is almost correct. Give the new view controller a team attribute and use this in the above predicate of its fetched results controller. You do not need any player or "playerDetails" information (they are linked to the team anyway).

Upvotes: 1

Related Questions