我有一组数组,它们都包含我创建的自定义Task对象的许多实例.我将数组保存到NSUserDefaults,如下所示: 自定义任务对象 class Task:NSObject, NSCoding { var name:String var notes:String var date:NSDat
自定义任务对象
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本身设置和检索数据.但是,尝试通过今日扩展程序检索数据时,此方法不起作用.
当尝试从今天的扩展名的.swift文件中检索时,我收到以下错误:
Failed to inherit CoreMedia permissions from 52550: (null)
Terminating app due to uncaught exception ‘NSInvalidUnarchiveOperationException’, reason: ‘* -[NSKeyedUnarchiver
decodeObjectForKey:]: cannot decode object of class (MyAppName.Task)
for key (NS.objects); the class may be defined in source code or a
library that is not linked’
我知道扩展可以读取数据,因为我打电话时:
if (defaults?.objectForKey("nowData") != nil){
print("there is data")
}
我得到了打印的回复..
我可以成功保存一个Integer并通过今天的扩展名检索,但不能通过objectForKey检索
我尝试了各种其他保存方法,包括.plist文件,但似乎没有任何工作.同样的错误不断发生.任何投入将不胜感激!
另一种方法是修复用于NSCoding的类的名称.你只需要使用:>序列化之前的NSKeyedArchiver.setClassName(“Task”,forClass:Task.self
>反序列化之前的NSKeyedUnarchiver.setClass(Task.self,forClassName:“Task”)
在需要的地方.
看起来iOS扩展名在类名前面加上扩展名.
