How do you save a custom class as an attribute of a CoreData entity in Swift 3?

后端 未结 1 472
遥遥无期
遥遥无期 2021-01-15 17:06

I have a CoreData Entity SavedWorkout. It has the following attributes:

completionCounter is an array of Bool, and work

1条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-15 17:48

    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
    }
    

    0 讨论(0)
提交回复
热议问题