Search code examples
swiftanyobject

Could not cast value of type 'Swift.Array<(Swift.String, Swift.String)>' to 'Swift.AnyObject'


My swift code look like below

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!)

I have error massage in console window while building code.

'Could not cast value of type 'Swift.Array<(Swift.String, Swift.String)>' (0xcce8098) to 'Swift.AnyObject' (0xcc8f00c).'

How can I archive Family.arrayTuple and unarchive Family.arrayTupleStorage?


Solution

  • 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")
        }
    }