【发布时间】:2016-02-18 06:08:56
【问题描述】:
我有一组数组,它们都包含我创建的自定义任务对象的多个实例。我将数组保存到 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")
}
}
保存:
let defaults = NSUserDefaults(suiteName: "group.com.myGroupName")
let nowData = NSKeyedArchiver.archivedDataWithRootObject(nowTasks)
defaults!.setObject(nowData, forKey: "nowData")
检索
let nowDataPull = defaults!.objectForKey("nowData") as? NSData
if let nowDataPull2 = nowDataPull{
let nowTasks2 = NSKeyedUnarchiver.unarchiveObjectWithData(nowDataPull2) as? [Task]
if let nowTasks21 = nowTasks2{
nowTasks = nowTasks21
}
}
上述方法适用于从 iPhone 本身设置和检索数据。但是,当尝试通过 today 扩展检索数据时,此方法不起作用。
当尝试从今天扩展的 .swift 文件中检索时,我收到以下错误:
无法从 52550 继承 CoreMedia 权限:(null)
由于未捕获的异常“NSInvalidUnarchiveOperationException”而终止应用程序,原因:'* -[NSKeyedUnarchiver decodeObjectForKey:]:无法解码类的对象(MyAppName.Task) 对于键(NS.objects);该类可以在源代码或 未链接的库'
我知道扩展程序可以读取数据,因为当我调用时:
if (defaults?.objectForKey("nowData") != nil){
print("there is data")
}
我收到了打印出来的回复..
我可以通过今天的扩展成功保存一个整数并检索,但不是objectForKey
我尝试了各种其他保存方法,包括 .plist 文件,但似乎没有任何效果。同样的错误不断发生。任何投入将不胜感激!
【问题讨论】:
-
我注意到错误指向
MyAppName.Task。在 Today Extension 中编译时,Task 类可能属于不同的模块? -
@MikePollard 我有一个名为“sharedCode.swift”的文件中的整个任务类声明。此文件已通过 Target Membership 对主应用程序和今天的扩展程序进行“检查”..
标签: ios swift nsuserdefaults today-extension