无法将 'Swift.Array<(Swift.String, Swift.String)>' 类型的值转换为 'Swift.AnyObject'
Could not cast value of type 'Swift.Array<(Swift.String, Swift.String)>' to 'Swift.AnyObject'
我的 swift
代码如下所示
Family.arrayTuple:[(String,String)]? = []
Family.arrayTupleStorage:String?
Family.arrayTupleStorage:String = (newDir! as NSString).stringByAppendingPathComponent("arrayTuple.archive")
NSKeyedArchiver.archiveRootObject(Family.arrayTuple! as! AnyObject, toFile: Family.arrayTupleStorage!)
我在构建代码时在控制台 window 中收到错误消息。
'Could not cast value of type 'Swift.Array<(Swift.String, Swift.String)>' (0xcce8098) to 'Swift.AnyObject' (0xcc8f00c).'
如何存档 Family.arrayTuple
和取消存档 Family.arrayTupleStorage
?
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")
}
}
我的 swift
代码如下所示
Family.arrayTuple:[(String,String)]? = []
Family.arrayTupleStorage:String?
Family.arrayTupleStorage:String = (newDir! as NSString).stringByAppendingPathComponent("arrayTuple.archive")
NSKeyedArchiver.archiveRootObject(Family.arrayTuple! as! AnyObject, toFile: Family.arrayTupleStorage!)
我在构建代码时在控制台 window 中收到错误消息。
'Could not cast value of type 'Swift.Array<(Swift.String, Swift.String)>' (0xcce8098) to 'Swift.AnyObject' (0xcc8f00c).'
如何存档 Family.arrayTuple
和取消存档 Family.arrayTupleStorage
?
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")
}
}