Swift NSCoding不工作

前端之家收集整理的这篇文章主要介绍了Swift NSCoding不工作前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在Swift中使用NSCoding有困难。我尝试实现协议,但是当我调用save()方法时,我会遇到崩溃。 Xcode把我拉到了encodeWithCoder的行上。这是我的代码,任何建议都会顺理成章。
class CourseList: NSObject,NSCoding {
    ...

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

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


    }
}

我写了save()和load()来调用ViewController。

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(History.courses,forKey: "courses")
    defaults.synchronize()
}

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];

}
自从提出这个问题以来,Swift已经有所改变了。我无法重现你所看到的错误,但是我能够使用下面的代码让NSCoding与Swift 1.0一起工作。
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() {
        NSUserDefaults.standardUserDefaults().removeObjectForKey("courseList")
    }

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

加载保存的实例,或者根据需要创建一个新的实例

// 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()
        courseLs.populateCourses()
        courseLs.save()
    }

猜你在找的Swift相关文章