嘿,我最近创建了一个应用程序,我想添加更多功能,但是保存应用程序数据的方式是使用Codable。问题是我想添加更多功能,当我尝试在数据模型中添加或删除变量时,它会完全擦除数据。我真的不希望我的用户丢失他们的数据。
我已经尝试过创建一个继承前一个类的新类,该类阻止擦除数据,但是它不允许我保存其他数据。这适用于使用最新版本的Swift和UIKit的iOS应用
我的加载数据功能
func loadClasses(){
if let data = try? Data(contentsOf: dataFilePath!){
let decoder = PropertyListDecoder()
do{
try classArray = decoder.decode([Course].self, from:
data)
}
catch{
print("error loading items \(error)")
}
}
if let data = try? Data(contentsOf: remindersDataFilePath!){
let decoder = PropertyListDecoder()
do{
try reminders = decoder.decode([Reminder].self, from:
data)
}
catch{
print("error loading items \(error)")
}
}
if let data = try? Data(contentsOf: completedDataFilePath!){
let decoder = PropertyListDecoder()
do{
try completedReminderes =
decoder.decode([Reminder].self, from: data)
}
catch{
print("error loading items \(error)")
}
}
if let data = try? Data(contentsOf: weightsDataFilePath!){
let decoder = PropertyListDecoder()
do{
try weights = decoder.decode(CourseWeights.self, from:
data)
print(weights.honors)
}
catch{
print("error loading items \(error)")
}
}
我的保存数据功能
func saveItems(){
let encoder = PropertyListEncoder()
do{
let data = try encoder.encode(classArray)
try data.write(to: dataFilePath!)
}catch{
print("Error encoding class array \(error)")
}
do{
let data = try encoder.encode(reminders)
try data.write(to: remindersDataFilePath!)
}catch{
print("Error encoding class array \(error)")
}
do{
let data = try encoder.encode(completedReminderes)
try data.write(to: completedDataFilePath!)
}catch{
print("Error encoding class array \(error)")
}
do{
let data = try encoder.encode(weights)
try data.write(to: weightsDataFilePath!)
}catch{
print("Error encoding weights array \(error)")
}
if(reminders.count>0){
for i in 0...reminders.count-1{
if(reminders.count > 0){
scheduleLocal(remind: reminders[i])
}
}
}
}
我想添加更多的数据模型
class oldReminder : Codable{
var name : String = "Untitled"
var completed : Bool = false
var willNotify : Bool = false
var due = Date()
var reminder = Date()
var course = Course()
let uuid = UUID().uuidString
}