是否可以使用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") } }