简体   繁体   中英

iOS (Swift): Core data transformable attributes

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM