Skip to content

Instantly share code, notes, and snippets.

@michaelmcguire
Last active August 29, 2015 14:07
Embed
What would you like to do?
NSKeyedArchiver breaking a Swift object
// Crash reproduction
// Xcode 6.1 GM
// Create new project, Single View Application, Language: Swift
// Copy code below into ViewController.swift
import UIKit
class MyClass : NSObject, NSCoding {
var myDictionary = [Int:Int]()
override init() {
}
required init(coder aDecoder: NSCoder) {
self.myDictionary = aDecoder.decodeObjectForKey("myDictionary") as [Int:Int]
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(self.myDictionary, forKey: "myDictionary")
}
func setInt(value: Int, atIndex index: Int) {
self.myDictionary[index] = value
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let fileManager = NSFileManager.defaultManager()
let documentDirectories = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask) as [NSURL]
let documentDirectory = documentDirectories[0]
let fileName = documentDirectory.URLByAppendingPathComponent("file.archive")
var myClass = MyClass()
myClass.setInt(10, atIndex: 0)
myClass.setInt(10, atIndex: 0)
NSKeyedArchiver.archiveRootObject(myClass, toFile: fileName.path!)
// CRASHOLA
myClass.setInt(10, atIndex: 0)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment