Swift-CoreData在删除后一直保持到重新编译



我正在尝试使用CoreData来保存我的用户数据。但是,删除的数据不会得到更新,即使在保存上下文时也是如此。只有在对应用程序进行另一次编译后,数据才会显示正确。

我已经在网上搜索了这个答案,许多人建议放入appDelegate.saveContext((。然而,即使在这之后,它也不起作用。

示例:我以用户1身份登录。用户1注销。用户2登录。用户1的数据仍在显示中。

删除:

func deleteCoreData(){
let fetchRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "User")
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)

guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
let context = appDelegate.persistentContainer.viewContext

do
{
try context.execute(deleteRequest)

} catch let error as NSError {
print(error)
}
appDelegate.saveContext()
}

读取:

func retrieveUserData() -> [String: String]{
var arr = [String: String]()
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
let context = appDelegate.persistentContainer.viewContext
let fetch = NSFetchRequest<User>(entityName: "User")
do {
let results = try context.fetch(fetch)

print("Fetching: ", results)
for result in results {
arr["name"] = result.name
arr["schoolName"] = result.schoolName
arr["school"] = result.school
arr["programCode"] = result.programCode
arr["classOf"] = result.classOf
arr["username"] = result.userId
arr["programName"] = result.programName
arr["username"] = result.username
arr["userId"] = result.userId
}
}
catch {
print("Cannot retrieve")
}
}
return arr
}

创建

func createNewCoreUser(login: String, data: [String: String]) {
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
print("CoreData has been created")
let context = appDelegate.persistentContainer.viewContext
guard let entityDescription = NSEntityDescription.entity(forEntityName: "User", in: context) else { return }
let newValue = NSManagedObject(entity: entityDescription, insertInto: context)
newValue.setValue(login, forKey: "userId")
newValue.setValue(data["name"], forKey: "name")
newValue.setValue(data["classOf"], forKey: "classOf")
newValue.setValue(data["programCode"], forKey: "programCode")
newValue.setValue(data["school"], forKey: "school")
newValue.setValue(data["schoolName"], forKey: "schoolName")
newValue.setValue(data["programName"], forKey: "programName")
newValue.setValue(data["username"], forKey: "username")
do {
try context.save()

(UIApplication.shared.connectedScenes.first?.delegate as? SceneDelegate)?.changeRootViewController(mainTabBarController)

} catch {
print("Storing data Failed")
}
}
}

解决了这个问题。注销并登录后,viewDidLoad不会运行,因此它不会运行我的Retrieve函数。

最新更新