How to save an array of custom structs to plist swift

后端 未结 1 1648
花落未央
花落未央 2021-01-16 22:08

I\'m trying to save alert data to a plist, it is in the form of an array of the class alertData, all the info i can find points to encoding it, and then putting it in the ar

1条回答
  •  礼貌的吻别
    2021-01-16 22:57

    You're not meant to call encodeWithCoder() yourself. Use NSKeyedArchiver and NSKeyedUnarchiver. The init(coder:) and encodeWithCoder() will be called as needed by the archiver / unarchiver.

    Place your NSCoding-compliant alertData instances (this should really be AlertData since class names should be proper case) into an array (or dictionary if you please) and do this:

    let archive = NSKeyedArchiver.archivedDataWithRootObject(yourArrayOfAlertData)
    

    In this case, archive will be an NSData instance.

    Update

    Actually, I guess I missed it the first time, but your encode...() method isn't right. At all. Consider the difference with:

    public func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeDouble(alertCounter, forKey:"Item1")
        aCoder.encodeObject(alertText, forKey:"Item2")
        aCoder.encodeObject(alertColor , forKey:"Item3")
        aCoder.encodeInteger(alertColorIndex, forKey:"Item4")
    }
    

    (Also consider naming your keys the same as their properties, like "alertCounter" for alertCounter.)

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