在保存数据时,正在检查实体中数据是否已经存在。这里的问题是上述方法无法按预期方式工作,当我第一次运行该应用程序时,它表明数据已经存在。请检查下面的代码并阐明一些内容。谢谢。
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
}
答案 0 :(得分:1)
首先,您在调用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
}