我一直在创建一个项目,只是为了弄乱核心数据以帮助自己学习它,但我已经来到每个项目的一部分,我只是无法弄清楚,这就是 - 我我正在尝试创建一个 UIAlert 窗口,它调用我编写的更新名称函数,用户可以输入一个新名称并点击更新,这看起来很简单,而且我已经得到了我需要的代码,减去一小部分。
我将发布我的代码,但我得到的错误是“无法将‘String’类型的值转换为预期的参数类型‘NameObject’”,据我所知,我的 NameObject 类是类型为 NSManagedObject,我只是不确定我哪里出错了或者该怎么做。
class NameObject: NSManagedObject {
static let entityName = "Person"
@NSManaged var name: String?}`class NameObject: NSManagedObject {
static let entityName = "Person"
@NSManaged var name: String? }
这是我的更新函数
func updateName(index: Int, newName: NameObject){
//1
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
// 2
peoples[index].name = newName.name
appDelegate.saveContext()
}
据我所知,它完全可以正常工作。
这是我的 UIAlert 代码,
@IBAction func updateNameButton(sender: AnyObject, indexPath: NSIndexPath) {
//customCell().updateNameAlert()
func updateNameAlert(){
let alert = UIAlertController(title: "Update",
message: "Please enter the new name.",
preferredStyle: .Alert)
// 1
let updateAction = UIAlertAction(title: "Save",
style: .Default){(_) in
let nameTextField = alert.textFields![0]
这是我遇到问题的地方:
self.updateName(indexPath.row, newName:(nameTextField.text!)) //Issue
self.tableView.reloadData()
}
// 2
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
alert.addTextFieldWithConfigurationHandler(nil)
alert.addAction(updateAction)
alert.addAction(cancelAction)
// 3
self.presentViewController(alert, animated: true, completion: nil)
}
}
如果需要任何进一步的信息,请告诉我;如果有帮助,我很乐意提供。
最佳答案
只需更改签名为参数 newName
取一个字符串,
这就是错误消息所说的内容。
func updateName(index: Int, newName: String){
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
peoples[index].name = newName
appDelegate.saveContext()
}
关于ios - SWIFT:更新现有的核心数据对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37489634/