Swift encode tuple using NSCoding(使用 NSCoding 对元组进行 Swift 编码)
问题描述
是否可以使用 NSCoding
存储元组?我有一个像 ((UInt8, UInt8), (UInt8, UInt8))
这样的元组.但是 aCoder.encodeObject(myTuple)
不起作用.我是否必须将元组转换为 NSData
或者这绝对不可能?感谢您的帮助
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
推荐答案
元组不能被编码,因为它不是一个类,但是一种方法是单独编码一个元组的每个组件,然后在解码时解码每个组件,然后将元组的值设置为根据解码内容构造的元组.
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")
}
}
这篇关于使用 NSCoding 对元组进行 Swift 编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 NSCoding 对元组进行 Swift 编码


- GPS状态的广播接收器? 2022-01-01
- URL编码Swift iOS 2022-01-01
- 如何在 iPhone 模拟器中重置 NSUserDefaults 数据? 2022-01-01
- SetOnItemSelectedListener上的微调程序错误 2022-01-01
- UITextView 内容插图 2022-01-01
- 类似于 Mail.app 的 iPad 模态视图控制器? 2022-01-01
- 使用自动布局向 UIScrollView 添加动态大小的视图 2022-01-01
- Xcode 7.3 中带有 UILabel 的 UIStackView 2022-01-01
- 网上有没有好的 UIScrollView 教程? 2022-01-01
- 在 Iphone SDK 的导航栏上添加多个按钮 2022-01-01