我引用programming guide将数据保存到CoreData,而我的实体代码是类别/扩展名(pic)
我使用performBackgroundTask来保存数据。 虽然,我保存后无法获取数据。 我必须强制关闭一个应用程序,然后再次重新打开它,我可以获取保存数据。
以下是我的代码。
将数据保存到CoreData的方法:
var container: NSPersistentContainer? =
(UIApplication.shared.delegate as? AppDelegate)?.persistentContainer
private func updateDatabase() {
container?.performBackgroundTask { [weak self] context in
if let name = self?.employeeName.text {
_ = try? Employee.findOrCreateEmployee(matching: name, in: context)
}
var date = (self?.startDate)!
let end = (self?.endDate)!
let fmt = DateFormatter()
fmt.dateFormat = "MM/dd"
while date <= end {
//print(fmt.string(from: date))
_ = try? Shift.findOrCreateShift(byEmployee: (self?.employeeName1.text)!, date: fmt.string(from: date), assignment: nil, in: context)
date = Calendar.current.date(byAdding: .day, value: 1, to: date)!
}
try? context.save()
}
}
从CoreData获取数据的方法:
var container: NSPersistentContainer? =
(UIApplication.shared.delegate as? AppDelegate)?.persistentContainer {
didSet { updateUI() }
}
private func updateUI() {
if let context = container?.viewContext {
let employeeRequest: NSFetchRequest<Employee> = Employee.fetchRequest()
employeeRequest.sortDescriptors = [NSSortDescriptor(
key: "created",
ascending: true,
)]
employees = try? context.fetch(employeeRequest)
let shiftsRequest: NSFetchRequest<Shift> = Shift.fetchRequest()
shiftsRequest.sortDescriptors = [ NSSortDescriptor(
key: "date",
ascending:true
)]
shifts = try? context.fetch(shiftsRequest)
}
}
有没有人有任何建议?
感谢。