Reputation: 211
I cannot for the life of me get this to work. I have a 'Match' entity and a 'Players' entity joined by a many-to-many relationship. For each match I am trying to create a string of names that are pulled from the Players entity in Core Data. Here is the latest incarnation of what I have been trying to achieve this with:
let players = matchData[indexPath.row].value(forKeyPath: "players") as? NSManagedObject
let playerNames = players?.value(forKey: "firstName") as? NSMutableArray
let playersString = playerNames?.componentsJoined(by: ",")
matchData
is the NSManagedObject
where my fetched data is held. "players" is the name of the relationship to the "Players" entity. And "firstName" is the attribute that I am trying to string together.
This however returns 'nil' for each match even though I know for sure that there are player records saved for each match. I can display other matchData items fine but am having trouble with this to-many relationship.
Upvotes: 1
Views: 579
Reputation: 119242
value(forKeyPath: "players") as? NSManagedObject
If players
is really a to-many relationship then this code will always return nil, because it will try to cast to an NSManagedObject
but the actual type is a Set
of NSManagedObject
s.
value(forKeyPath: "players") as? Set<NSManagedObject>
will get you past the first hurdle.
You'd be doing yourself a favour to specify managed object subclasses as well, then you'll have properties generated for all of these things which will make your code much cleaner and easier to understand.
Upvotes: 1