是否可以使用存储元组NSCoding?我有一个类似的元组((UInt8, UInt8), (UInt8, UInt8))。但是aCoder.encodeObject(myTuple)不起作用。我必须将元组转换为NSData还是绝对不可能?谢谢你的帮助
NSCoding
((UInt8, UInt8), (UInt8, UInt8))
aCoder.encodeObject(myTuple)
NSData
无法对元组进行编码,因为它不是类,但是一种方法是分别对元组的每个组成部分进行编码,然后在解码时对每个组成部分进行解码,然后将元组的值设置为根据解码内容构造的元组。
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") } }