Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift encode tuple using NSCoding

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

like image 707
borchero Avatar asked Mar 08 '15 17:03

borchero


1 Answers

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")
    }
}
like image 71
Ian Avatar answered Sep 16 '22 21:09

Ian