gpt4 book ai didi

swift NSCoding 不工作

转载 作者:IT王子 更新时间:2023-10-29 05:09:58 26 4
gpt4 key购买 nike

我在 Swift 中使用 NSCoding 时遇到问题。我试图实现该协议(protocol),但每当我调用我的 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 NSCoding 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24238868/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com