I have a simple Time
class that adopts NSCoding
protocol:
class Time: NSObject, NSCoding {
var hours: Int
func encode(with aCoder: NSCoder) {
aCoder.encode(self.hours, forKey: "hours")
}
public required init?(coder aDecoder: NSCoder) {
guard let hours = aDecoder.decodeObject(forKey: "hours") as? Int
else { return nil }
self.hours = hours
}
init(hours: Int) {
self.hours = hours
}
}
which I want to be a Transformable
attribute to my Watch
entity:
final class Watch: NSManagedObject {
@NSManaged public fileprivate(set) var time: Time
}
as shown here:
I successfully save this to the managed object context but when I reload the app the time
attribute is nil
.
Am I missing something here? Why doesn't this property successfully save? This seems to be all that is required in other posts.
Thanks a lot for any help!
The suggestion in the comments of the question by @IraniyaNaynesh is a red herring.
The answer turns out to be quite simple. Change decodeObject
to decodeInteger
in the init?(coder aDecoder: NSCoder)
method and the data restores the BLOBS
, which are not nil
and have been saved successfully, from the SQLite database.