1

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?

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
WoderMan
  • 53
  • 1
  • 12
  • 1
    You can't archive tuples with NSKeyedArchiver: http://stackoverflow.com/questions/28929897/swift-encode-tuple-using-nscoding – Eric Aya Feb 04 '16 at 12:42
  • The NSKeyedArchiver is just context for the actual error here: you can't cast a tuple to `AnyObject`: tuples are value types and `AnyObject` [_"can (only) represent an instance of any class type"_](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TypeCasting.html). The following will yield the same error: `var foo = (1, 2)`, `var bar = foo as! AnyObject`. You can seemingly cast, however, an integer (`var foo = 1` above) to `AnyObject`: this is slightly misleading, as `AnyObject` internally stores the int as an class instance (`__NSCFNumber`). – dfrib Feb 04 '16 at 13:40
  • i can solve the problem! good tip is stackoverflow.com/questions/28929897/… – Eric D. yesterday thanks!! – WoderMan Feb 06 '16 at 11:14

1 Answers1

1
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")
    }
}
Pavlos
  • 906
  • 1
  • 11
  • 29
WoderMan
  • 53
  • 1
  • 12