chris chris - 6 months ago 26
Swift Question

Swift NSCoding Not working

I'm having trouble using

in Swift. I have attempted to implement the protocol but I get a crash whenever I call my
method. Xcode pulls me up on the line in
. Here's my code, any suggestions would go along way.

class CourseList: NSObject, NSCoding {

init(coder aDecoder: NSCoder!){
if aDecoder != nil { = aDecoder.decodeObjectForKey("courses") as Dictionary<String,course>

func encodeWithCoder(aCoder: NSCoder!) {
aCoder!.encodeObject(, forKey: "courses") // EXC_BAD_INSTRUCTOIN


I wrote
to call in a

func save() {
var archivedObject = NSKeyedArchiver.archivedDataWithRootObject(History) //NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
var defaults = NSUserDefaults.standardUserDefaults() //[defaults setObject:archivedObject forKey:<key_for_archived_object>];
defaults.setObject(, forKey: "courses")

func load() {
var defaults = NSUserDefaults.standardUserDefaults() // NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
var archivedObject = defaults.objectForKey("courses") as NSData // NSData *archivedObject = [defaults objectForKey:<key_for_archived_object>];
History = NSKeyedUnarchiver.unarchiveObjectWithData(archivedObject) as Dictionary<String,course> //<your_class> *obj = (<your_class> *)[NSKeyedUnarchiver unarchiveObjectWithData:archivedObject];



Quite a bit has changed with Swift since this question was asked. I can't reproduce the error you're seeing, but I was able to get NSCoding to work with Swift 1.0 with the code below.

class CourseList: NSObject, NSCoding
    var myCourses: Dictionary<String, String>?

    override init() {}

    required init(coder aDecoder: NSCoder) {
        self.myCourses  = aDecoder.decodeObjectForKey("myCourses") as? Dictionary

    func encodeWithCoder(aCoder: NSCoder) {
        if let courses = self.myCourses{
            aCoder.encodeObject(courses, forKey: "myCourses")

    func populateCourses() {
        self.myCourses = ["cs101": "Hello World"]

    func save() {
        let data = NSKeyedArchiver.archivedDataWithRootObject(self)
        NSUserDefaults.standardUserDefaults().setObject(data, forKey: "courseList")

    func clear() {

    class func loadSaved() -> CourseList? {
        if let data = NSUserDefaults.standardUserDefaults().objectForKey("courseList") as? NSData {
            return NSKeyedUnarchiver.unarchiveObjectWithData(data) as? CourseList
        return nil

To load a saved instance or create a new one if needed

    // Try loading a saved version first
    if let courseLs = CourseList.loadSaved() {
        println("loaded Save CourseList")
    } else {
        // Create a new Course List
        let courseLs: CourseList = CourseList()