我更改了结构并进行了迁移(创建了新模型),添加并显示了数据,一切正常,但是当我重新加载应用程序时,核心数据为空,是什么问题?
static func saveToCoreData(_ words: Words?){
DispatchQueue.main.async {
coreDataResult(data: [words?.word, words?.translation], completion: { (result, taskObject, context) in
do {
let fetchedEntities = try context.fetch(result) as! [Favorite]
if let _ = fetchedEntities.first?.word {
print("the element already have in coreData")
} else {
taskObject?.setValue(words?.word, forKey: "word")
taskObject?.setValue(words?.translation, forKey: "translation")
taskObject?.setValue(words?.descript, forKey: "wordDesc")
taskObject?.setValue(words?.translDesc, forKey: "translDesc")
do {
try context.save()
} catch {
print(error)
}
}
} catch {}
})
}
}
static func coreDataResult(data: [[String?]?]?, completion: @escaping (NSFetchRequest<NSFetchRequestResult>, Favorite?, NSManagedObjectContext) -> ()){
guard let w = data?.first, let word = w, let t = data?.last, let transl = t else { return }
DispatchQueue.main.async {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
guard let entity = NSEntityDescription.entity(forEntityName: "Favorite", in: context) else { return }
guard let taskObject = NSManagedObject(entity: entity, insertInto: context) as? Favorite else { return }
let predicate = NSPredicate(format: "word == %@", word)
let predicate2 = NSPredicate(format: "translation == %@", transl)
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Favorite")
let andPredicate = NSCompoundPredicate(type: .and, subpredicates: [predicate, predicate2])
fetchRequest.predicate = andPredicate
completion(fetchRequest, taskObject, context)
}
}
答案 0 :(得分:1)
我决定了