且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Swift 3中将自定义类保存为CoreData实体的属性?

更新时间:2022-02-04 15:38:52

问题是 WorkoutRoutine 本身是一个自定义类,由于出现错误,它不符合NSCoding,因此 aCoder.encode(routine,forKey: routine)真的不知道如何编码,以及 routine = aDecoder.decodeObject(forKey: routine)一样! [WorkoutRoutine] 不知道如何解码。

The issue is that WorkoutRoutine is itself a custom class and as of your error it is not NSCoding compliant, therefore aCoder.encode(routine, forKey: "routine") doesn't really know how to encode it, as well as routine = aDecoder.decodeObject(forKey: "routine") as! [WorkoutRoutine] doesn't know how to decode it.

虽然没什么关系,但是请为编码器和编码器初始化程序尝试一种更安全的方法因为如果编码器不包含您要查找的键(由于任何原因),力解开可能会导致崩溃

Not really related, but please try a safer approach for your coder and encoder initializer as the force unwrap might cause crashes if the encoder does not contain the keys you are looking for (for any reason)

required init?(coder aDecoder: NSCoder) {
    guard let name = aDecoder.decodeObject(forKey: "name") as? String,
        let imageName = aDecoder.decodeObject(forKey: "imageName") as? String,
        let routine = aDecoder.decodeObject(forKey: "routine") as? [WorkoutRoutine],
        let shortDescription = aDecoder.decodeObject(forKey: "shortDescription") as? String else {
            return nil
    }
    self.name = name
    self.imageName = imageName
    self.routine = routine
    self.shortDescription = shortDescription
}