使用 NSCoding 对元组进行 Swift 编码

Swift encode tuple using NSCoding(使用 NSCoding 对元组进行 Swift 编码)

本文介绍了使用 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 编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:使用 NSCoding 对元组进行 Swift 编码

基础教程推荐