出于实践原因,我正在使用 CoreData 制作一个小应用程序。我有一个带有游戏的类并且游戏有玩家。现在当我想访问我保存在我的 CoreData 中的最后一个游戏时,应用程序崩溃并且我收到以下错误(但代码正在编译):
MyApp[89980:1675908] -[Player initWithCoder:]: 无法识别的选择器发送到实例
所以我有一个:
- 抽象类 GAME
- 类Timer,它是GAME的子类
- TIMER中 P1 和 P2 的播放器
并且代码看起来像这样:
这是定时器的类 - 它从之前的设置中获取一个定时器对象
struct Timer : View {
@Environment(\.managedObjectContext) var moc
@Binding var game : Timer
var body : some View {
...
Button(action: {
let finishedGame : Timer = Timer(context: moc)
let p1 : Player = Player(context: moc)
let p2 : Player = Player(context: moc)
//Player1
p1.playerID = UUID()
p1.playerName = "First"
p1.playerPoints = 0
p1.playerColor = Color.red
p1.isPlaying = false
//Player2
p2.playerID = UUID()
p2.playerName = "Second"
p2.playerPoints = 10
p2.playerColor = Color.blue
p2.isPlaying = false
//game
finishedGame.id = UUID()
finishedGame.date = Date.now
finishedGame.gameRounds = 10 //just for example
finishedGame.playerOne = p1
finishedGame.playerTwo = p2
finishedGame.seconds = 60
finishedGame.displayTime = false
do{ try moc.save() } catch { print("Couldn't save game") }
}, label: {
Text("save")
})
}
}
在我的 viewLastGamesView 中,我想查看我的最后一场比赛 - 这里发生了错误:
struct LastGamesView : View {
@FetchRequest(entity: Game.entity(), sortDescriptors: []) var games : FetchedResults<Game>
var body: some View{
List{
ForEach(games){ game in
HStack{
Text("\(game.date)")
}
}
}
}
}
谢谢你的帮助!