Swift 使用 NSCoding 编码元组

Swift encode tuple using NSCoding

是否可以使用 NSCoding 存储元组?我有一个像 ((UInt8, UInt8), (UInt8, UInt8)) 这样的元组。但是 aCoder.encodeObject(myTuple) 不起作用。我必须将元组转换为 NSData 还是这绝对不可能?感谢您的帮助

元组无法编码,因为它不是 class,但一种方法是分别对元组的每个组件进行编码,然后在解码时对每个组件进行解码,然后将元组的值设置为从解码内容构造的元组。

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")
    }
}

我只想分享我的代码,它有一些基于 Ian 代码的更新。 我用我的创建了元素的类别/子类别列表。

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)
} }