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
Swift encode tuple using NSCoding
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")
}
}
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)
} }
© 2022 - 2024 — McMap. All rights reserved.