GabrielMSC GabrielMSC - 2 years ago 175
iOS Question

SWIFT: Updating an existing core data object

quick question I've been stuck on, I've been creating a project just to mess around with core data to help myself learn it, but I've come to the part of every project where I just simply can't figure this out, here it is- I am trying to create a UIAlert window, that calls the update name function I've written, that a user can enter a new name and hit update, seems easy enough, and I've got the code I need, minus one tiny piece.

I will post my code, but the error I'm getting is "Cannot convert value of type 'String' to expected argument type 'NameObject'", which I understand, my NameObject class is of type NSManagedObject, I just am not sure where I went wrong or what to do.

class NameObject: NSManagedObject {
static let entityName = "Person"
@NSManaged var name: String?}`class NameObject: NSManagedObject {
static let entityName = "Person"
@NSManaged var name: String? }

Here is my update function

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


totally works fine, as far as I know.

Here is my code for the UIAlert,

@IBAction func updateNameButton(sender: AnyObject, indexPath: NSIndexPath) {

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]

Here is where I am having my issue

self.updateName(indexPath.row, newName:(nameTextField.text!))


// 2
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)


// 3
self.presentViewController(alert, animated: true, completion: nil)



if any further information is wanted let me know, glad to provide if it helps.

Answer Source

Just change the signature to take a string for parameter newName,
that's what the error message says.

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download