我正在开发一个第一次使用 Xcode 数据库的应用程序。通过遵循在线教程,我了解了如何逐步完成此操作,但是当我测试应用程序时,当它到达将数据保存到数据库中的行时,我会遇到运行时异常。
这是我到目前为止写的代码,想法是当按下星号按钮时,用户信息将被保存
@IBAction func favPressed(sender: AnyObject) {
let appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
let context:NSManagedObjectContext = appDel.managedObjectContext
// here is where the app crushes:
let newFav = NSEntityDescription.insertNewObjectForEntityForName("FavoriteUser", inManagedObjectContext: context) as! NSManagedObject
newFav.setValue("" + userName, forKey: "uName")
newFav.setValue("" + userEmail, forKey: "uEmail")
newFav.setValue("" + userPhone, forKey: "uPhone")
do{
try context.save()
}
catch{
print(error)
}
print("user saved to favs")
}
我不知道为什么会发生这种情况,我不知道这是否会有所帮助,但请注意我将核心数据用于现有的大项目。我在 appDelegate.swift 中添加了 CoreData.framework 和所需的功能