Swift encode tuple using NSCoding

落花浮王杯 提交于 2019-11-28 00:26:43

问题


Is it possible to store a tuple using NSCoding? I have a tuple like ((UInt8, UInt8), (UInt8, UInt8)). But aCoder.encodeObject(myTuple) doesn't work. Do I have to convert the tuple into NSData or is this absolutely not possible? Thanks for any help


回答1:


Tuple cannot be encoded because it is not a class, but one approach is to encode each component of a tuple separately and then upon decoding you decode each component and then set the value of the tuple to a tuple constructed from the decoded content.

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        let obj = SomeClass()
        obj.foo = (6,5)

        let data = NSKeyedArchiver.archivedDataWithRootObject(obj)
        NSUserDefaults.standardUserDefaults().setObject(data, forKey: "books")

        if let data = NSUserDefaults.standardUserDefaults().objectForKey("books") as? NSData {
            let o = NSKeyedUnarchiver.unarchiveObjectWithData(data) as SomeClass
            println(o.foo) // (Optional(6), Optional(5))

        }
    }
}

class SomeClass: NSObject, NSCoding {
    var foo: (x: Int?, y: Int?)!

    required convenience init(coder decoder: NSCoder) {
        self.init()
        let x = decoder.decodeObjectForKey("myTupleX") as Int?
        let y = decoder.decodeObjectForKey("myTupleY") as Int?
        foo = (x,y)
    }

    func encodeWithCoder(coder: NSCoder) {
        coder.encodeObject(foo.x, forKey: "myTupleX")
        coder.encodeObject(foo.y, forKey: "myTupleY")
    }
}



回答2:


I just want to share my code which has some updates based on Ian's code. I used mine to create a list of category / subcategory of elements.

class catSubcatOption: NSObject, NSCoding  {

var element: (x: String, y: String)!

override init() {

}

public func encode(with aCoder: NSCoder) {
    aCoder.encode(element.category, forKey: "category")
    aCoder.encode(element.subcategory, forKey: "subcategory")
}

required init(coder decoder: NSCoder) {
    let category = decoder.decodeObject(forKey: "category") as! String
    let subcategory = decoder.decodeObject(forKey:"subcategory") as! String
    element = (category,subcategory)
} }


来源:https://stackoverflow.com/questions/28929897/swift-encode-tuple-using-nscoding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!