Swift使用NSCoding编码元组

时间:2015-03-08 17:58:46

标签: swift tuples nscoding

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

2 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:0)

我只想分享我的代码,该代码基于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)
} }