gpt4 book ai didi

ios - 在保存到 coredata -Swift 之前检查数据是否存在

转载 作者:行者123 更新时间:2023-11-30 11:18:44 29 4
gpt4 key购买 nike

保存数据时,检查数据是否已存在于实体中。这里的问题是上面的方法没有按预期工作,当我第一次运行应用程序时,它显示数据已经存在。请检查下面的代码并阐明一些情况。谢谢。

func someEntityExists(id: String, entityName: String, type : String, fieldName : String) -> Bool {
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: entityName)
if type == "String"{
fetchRequest.predicate = NSPredicate(format: "\(fieldName) == %@", id)
}else{
fetchRequest.predicate = NSPredicate(format: "\(fieldName) == %d", id)

}

var results: [NSManagedObject] = []

do {
results = try self.persistentContainer.viewContext.fetch(fetchRequest)
}
catch {
print("error executing fetch request: \(error)")
}

return results.count > 0
}

下面是调用此函数来保存用户信息的代码。

  func saveUserInfo(detail:[String:Any])-> Bool
{
let context = self.persistentContainer.viewContext
var isSave : Bool = false
let entity = NSEntityDescription.entity(forEntityName: "User", in: context)
let newUser = NSManagedObject(entity: entity!, insertInto: context)
newUser.setValue(detail["id"], forKey: "id")
newUser.setValue(detail["api_token"], forKey: "api_token")
newUser.setValue(detail["username"], forKey: "username")
newUser.setValue(detail["email"], forKey: "email")
if let category = detail["firstname"] as? String {
newUser.setValue(detail["firstname"], forKey: "firstname")
}
if let category = detail["middlename"] as? String {
newUser.setValue(detail["middlename"], forKey: "middlename")
}
if let category = detail["lastname"] as? String {
newUser.setValue(detail["lastname"], forKey: "lastname")
}

do {

let isExist = someEntityExists(id: newUser.value(forKey: "email") as! String , entityName: "User", type: "String", fieldName: "email")
if isExist == true {
// don't save anything
print("Data is already present ")
}else{
try context.save()
isSave = true
}
} catch {

print("Failed saving")
isSave = false
}



return isSave

}

最佳答案

首先,您在调用 someEntityExists 之前在托管上下文中创建一个 User 对象,因此该对象很可能会包含在提取中,即使尚未保存。

在创建新用户实体之前调用 someEntityExists 来查看是否应该继续

func saveUserInfo(detail:[String:Any])-> Bool {
if someEntityExists(id: detail["email"] , entityName: "User", type: "String", fieldName: "email") {
print("Data is already present")
return false
}
//else create and save new user
}

关于ios - 在保存到 coredata -Swift 之前检查数据是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51518269/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com