我创建一个数据管理器模型,这里是:
public class DataManager {
// get documents directiory
static fileprivate func getDocumentDirectory() -> URL {
if let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
return url
} else {
fatalError("Unable to access document directiory")
}
}
// save any kind of codable objects
static func save <T: Encodable> (_ object: T, with filename: String) {
let url = getDocumentDirectory().appendingPathComponent(filename, isDirectory: false)
let encoder = JSONEncoder()
do {
let data = try encoder.encode(object)
if FileManager.default.fileExists(atPath: url.path) {
try FileManager.default.removeItem(at: url)
}
FileManager.default.createFile(atPath: url.path, contents: data, attributes: nil)
} catch {
fatalError(error.localizedDescription)
}
}
// Load any kind of codable object
static func load <T: Decodable> (_ filename: String, with type: T.Type) -> T {
let url = getDocumentDirectory().appendingPathComponent(filename, isDirectory: false
)
if !FileManager.default.fileExists(atPath: url.path) {
fatalError("File not found at path \(url.path)")
}
if let data = FileManager.default.contents(atPath: url.path) {
do {
let model = try JSONDecoder().decode(type, from: data)
return model
} catch {
fatalError(error.localizedDescription)
}
} else {
fatalError("Data is unavailable at path \(url.path)")
}
}
// Load data from a file
static func loadData(_ filename: String) -> Data? {
let url = getDocumentDirectory().appendingPathComponent(filename, isDirectory: false
)
if !FileManager.default.fileExists(atPath: url.path) {
fatalError("File not found at path \(url.path)")
}
if let data = FileManager.default.contents(atPath: url.path) {
return data
} else {
fatalError("Data is unavailable at path \(url.path)")
}
}
//Load all files from a directory
static func loadAll <T:Decodable> (_ type: T.Type) ->[T] {
do {
let files = try FileManager.default.contentsOfDirectory(atPath: getDocumentDirectory().path)
var modelObjects = [T]()
for filename in files {
modelObjects.append(load(filename, with: type))
}
return modelObjects
} catch {
fatalError("Could not load any files")
}
}
//Delete file
static func delete (_ filename: String) {
let url = getDocumentDirectory().appendingPathComponent(filename, isDirectory: false)
if FileManager.default.fileExists(atPath: url.path) {
do {
try FileManager.default.removeItem(at: url)
} catch {
fatalError(error.localizedDescription)
}
}
}
}
我添加了所有需要以某种方式回答我的代码。
在此数据管理器中,我在控制器中创建了一个数组以显示数据
var activity = DataManager.loadAll(Activity.self)
当我从该方法保存数据时,它将完美保存,但是此数组无法立即更新以从中获取数据,因此我必须关闭应用程序,当我再次打开它时,该数组将更新为最新数据。您对此有何建议? 非常感谢
在我的模型中,我还具有保存数据的功能
func saveItem() {
DataManager.save(self, with: identifier.uuidString)
}
然后在控制器中保存类似的数据
let newActivity = Activity(title: "Test todo", isDone: false, DeteOfCreation: Date(), identifier: UUID())
newActivity.saveItem()