Fetch attributes from to many relationship in Swift Core Data

时间:2017-04-24 08:51:48

标签: swift core-data

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.

1 个答案:

答案 0 :(得分:1)

value(forKeyPath: "players") as? NSManagedObject

如果players确实是多对多关系,则此代码将始终返回nil,因为它会尝试转换为NSManagedObject,但实际类型为Set { {1}}秒。

NSManagedObject会让你超越第一道障碍。

您也可以自己帮忙指定托管对象子类,然后您将为所有这些内容生成属性,这将使您的代码更清晰,更易于理解。