我的数据不会取消存档,但是当用户使用该应用程序时会正确保存。在我编写的其他应用程序中,我已经检查过并且使用了相同的代码。
func loadSurveys(){
guard let surveyData = UserDefaults.standard.object(forKey: "addedSurveys") as? NSData else {
print("No surveys found")
initSurveysArray()
return
}
guard let allSurveys = NSKeyedUnarchiver.unarchiveObject(with: surveyData as Data) as? addedSurveys else {
print("Could not unarchive")
return
}
surveys = allSurveys.surveys
}
这里也是我保存它的地方,
func saveSurveys(){
let surveyData = NSKeyedArchiver.archivedData(withRootObject: surveys)
UserDefaults.standard.set(surveyData, forKey: "addedSurveys")
}
这是我的addSurveys类,并且已经为其中引用的所有类实现了NSCoding。
class addedSurveys: NSObject, NSCoding{
var surveys = [survey]()
override init(){}
convenience init(survey : [survey])
{
self.init()
self.surveys = survey
}
required init?(coder aDecoder: NSCoder) {
self.surveys = aDecoder.decodeObject(forKey: "addedSurveys") as! [survey]
}
func encode(with aCoder: NSCoder) {
aCoder.encode(surveys, forKey: "addedSurveys")
}
}
这是调查对象:
class survey: NSObject, NSCoding{
func encode(with aCoder: NSCoder) {
aCoder.encode(areas, forKey: "areas")
aCoder.encode(settings, forKey: "setting")
aCoder.encode(overview, forKey: "overview")
aCoder.encode(name, forKey: "name")
}
required init?(coder aDecoder: NSCoder) {
self.areas = aDecoder.decodeObject(forKey: "area") as? [areaProps] ?? [areaProps()]
self.settings = aDecoder.decodeObject(forKey: "settings") as? companySettings ?? companySettings()
self.overview = aDecoder.decodeObject(forKey: "overview") as? overviewProps ?? overviewProps()
self.name = aDecoder.decodeObject(forKey: "name") as? String ?? "ok"
}
var areas = [areaProps]()
var settings = companySettings(manager: "")
var overview = overviewProps(x: "", y: "", a: "", b: "", c: "", d: "", e: "", f: "", st: "", ct: "", stt: "")
var name = ""
override init() {
}
convenience init(areas: [areaProps], settings: companySettings, overview: overviewProps, name : String)
{
self.init()
self.areas = areas
self.settings = settings
self.overview = overview
self.name = name
}
}