无法将数据从 NSUserDefaults 检索到今天的扩展 (Swift)

Mat*_*ler 4 nsuserdefaults ios swift today-extension

我有一组数组,它​​们都包含我创建的自定义 Task 对象的多个实例。我将数组保存到 NSUserDefaults 如下:

自定义任务对象

class Task:NSObject, NSCoding {
    var name:String
    var notes:String
    var date:NSDate
    var dateUse:Bool
    var taskCompleted:Bool

    init(name:String, notes:String, date:NSDate, dateUse:Bool, taskCompleted:Bool){
        self.name = name
        self.notes = notes
        self.date = date
        self.dateUse = dateUse
        self.taskCompleted = taskCompleted
    }

    required init(coder decoder: NSCoder){
        self.name = decoder.decodeObjectForKey("name") as! String
        self.notes = decoder.decodeObjectForKey("notes") as! String
        self.date = decoder.decodeObjectForKey("date") as! NSDate
        self.dateUse = decoder.decodeObjectForKey("dateUse") as! Bool
        self.taskCompleted = decoder.decodeObjectForKey("taskCompleted") as! Bool
    }

    func encodeWithCoder(coder: NSCoder) {
        coder.encodeObject(self.name, forKey: "name")
        coder.encodeObject(self.notes, forKey: "notes")
        coder.encodeObject(self.date, forKey: "date")
        coder.encodeObject(self.dateUse, forKey: "dateUse")
        coder.encodeObject(self.taskCompleted, forKey: "taskCompleted")
    }
}
Run Code Online (Sandbox Code Playgroud)

保存:

let defaults = NSUserDefaults(suiteName: "group.com.myGroupName")

let nowData = NSKeyedArchiver.archivedDataWithRootObject(nowTasks)
defaults!.setObject(nowData, forKey: "nowData")
Run Code Online (Sandbox Code Playgroud)

检索

let nowDataPull = defaults!.objectForKey("nowData") as? NSData
if let nowDataPull2 = nowDataPull{
   let nowTasks2 = NSKeyedUnarchiver.unarchiveObjectWithData(nowDataPull2) as? [Task]
   if let nowTasks21 = nowTasks2{
      nowTasks = nowTasks21
   }
}
Run Code Online (Sandbox Code Playgroud)

上述方法适用于从 iPhone 本身设置和检索数据。但是,当尝试通过今天的扩展检索数据时,此方法不起作用。

尝试从 today 扩展的 .swift 文件中检索时,出现以下错误:

  • 无法从 52550 继承 CoreMedia 权限:(空)

  • 由于未捕获的异常“NSInvalidUnarchiveOperationException”而终止应用程序,原因:“* -[NSKeyedUnarchiver decodeObjectForKey:]:无法为密钥(NS.objects)解码类(MyAppName.Task)的对象;该类可以在源代码或未链接的库中定义'


我知道扩展可以读取数据,因为当我打电话时:

if (defaults?.objectForKey("nowData") != nil){
   print("there is data")
}
Run Code Online (Sandbox Code Playgroud)

我得到了打印的回复..


我可以成功保存一个整数并通过今天的扩展检索,但不能 objectForKey


我尝试了各种其他保存方法,包括 .plist 文件,但似乎没有任何效果。同样的错误不断发生。任何投入将不胜感激!

ter*_*ina 5

另一种方法是修复用于 NSCoding 的类的名称。您只需要使用:

  • NSKeyedArchiver.setClassName("Task", forClass: Task.self 序列化前
  • NSKeyedUnarchiver.setClass(Task.self, forClassName: "Task") 反序列化之前

任何需要的地方。

看起来 iOS 扩展在类名前加上扩展名。

  • 这是 iOS 扩展最通用的解决方案(应该是公认的答案)。 (2认同)