我的应用程序仍处于开发阶段,我正在尝试注册用户。我想检查核心数据中是否有现有用户,如果结果返回0,那么我将添加一个新用户。如果没有,我将更新从服务器端获取的现有用户。我也知道目前,我的核心数据是空。但是,当我尝试获取数据时,在
行 let searchResult = try managedContext.fetch(fetchRequest) as! [User]
它转到catch语句并打印错误。
错误Domain = Foundation._GenericObjCError Code = 0"(null)"
以下是我的代码。尝试在Google上搜索确切的错误代码,但我找不到任何错误代码。
func SaveToCoreData(){
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "User")
let managedContext = appDelegate.persistentContainer.viewContext
do{
let searchResult = try managedContext.fetch(fetchRequest) as! [User]
let entity = NSEntityDescription.entity(forEntityName: "User", in: managedContext)
let newUser = NSManagedObject(entity: entity!, insertInto: managedContext)
if(searchResult.count == 0){
newUser.setValue(emailField, forKey: "email")
newUser.setValue(jsonReply["profilePicture"].stringValue, forKey: "profilePicture")
do{
try managedContext.save()
} catch let error as NSError{
ShowAlert(title: "", message: error.description)
}
}
else if(searchResult.count == 1){
let updateUser = user[0]
updateUser.setValue(emailField, forKey: "email")
updateUser.setValue(jsonReply["profilePicture"].stringValue, forKey: "profilePicture")
do{
try managedContext.save()
self.ShowTabBar()
} catch let error as NSError{
ShowAlert(title: "", message: error.description)
}
}
} catch let error as NSError{
print(error)
}
}