Swift encode tuple using NSCoding
Asked Answered
E

2

10

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

Everhart answered 8/3, 2015 at 17:58 Comment(0)
J
6

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")
    }
}
Joanne answered 8/3, 2015 at 18:46 Comment(0)
S
1

I just want to share my code which has some updates based on Ian's code. I used mine to create a list of category / subcategory of elements.

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)
} }
Superable answered 7/10, 2017 at 16:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.