使用 NSCoding Swift 编码元组 [英] Swift encode tuple using NSCoding

查看:35
本文介绍了使用 NSCoding Swift 编码元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

元组不能被编码,因为它不是一个类,但一种方法是分别对元组的每个组件进行编码,然后在解码时解码每个组件,然后将元组的值设置为根据解码内容构造的元组.

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

这篇关于使用 NSCoding Swift 编码元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆