SWIFT:更新现有核心数据对象

时间:2016-05-27 17:54:00

标签: ios swift cocoa cocoa-touch core-data

我一直在创建一个项目,只是为了帮助我自己学习核心数据,但是我来到了每个项目的一部分,我根本无法解决这个问题,这里是 - 我我正在尝试创建一个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)
    }
}

如果需要任何进一步的信息,请告诉我;如果它有帮助,我很乐意提供它。

1 个答案:

答案 0 :(得分:5)

只需更改签名即可获取参数newName的字符串,
这就是错误信息所说的内容。

func updateName(index: Int, newName: String){
   let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
   peoples[index].name = newName
   appDelegate.saveContext()

}
相关问题