我写了save()和load()来调用VIEwController。
@H_301_1@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一起工作。 @H_301_1@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 }}加载保存的实例,或者根据需要创建一个新的实例
@H_301_1@// 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 NSCoding不工作全部内容,希望文章能够帮你解决Swift NSCoding不工作所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)