Core Data Update in swift while selecting any row

2019-03-03 14:24发布

问题:

I have got a scenario in which I have 2 VC which are -

VC1 - To enter detail & save the data. VC2 - To display the datas in a table view.

Now I want that whenever I select any particular row I would update my Database at the particular row. For that I am passing the selected managed object at that particular row for which I use the following code.

VC2 class name - ViewController

Code to fetch request -

func fetchData()
{
    let appdelegate = UIApplication.sharedApplication().delegate as! AppDelegate

    let managedContext = appdelegate.managedObjectContext

    let fetchRequest = NSFetchRequest(entityName: "Person")

    do
    {
        people = try managedContext.executeFetchRequest(fetchRequest) as! [NSManagedObject]
        print(people)
        print("FETCHING DATA")

    }
    catch let error as NSError
    {
        print("could not fetch \(error), \(error.userInfo)")
    }

    }

Code to pass the data in selected row -

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
    {
        if segue.identifier == "segueupdate"
        {

            let update = segue.destinationViewController as! EnterDetailViewController
          //  var managedobject = NSManagedObject()
            let indexpath = self.tableview.indexPathForSelectedRow

            let row = indexpath?.row
          let  managedobject = people[row!]

            update.managedobjectt = managedobject

        }
    }

VC2 class name - EnterDetailViewController

class EnterDetailViewController: UIViewController {

    @IBOutlet weak var nametextfield: UITextField!
    var managedobjectt = NSManagedObject()
    override func viewDidLoad() {
        super.viewDidLoad()
        if let s = managedobjectt.valueForKey("name") as? String
        {
            nametextfield.text = s //here I show the user the existing name value
        }

    }

Now in my save function I do -

@IBAction func savedata(sender: AnyObject)
    {

    let appdelegate = UIApplication.sharedApplication().delegate as! AppDelegate

    let managedcontext = appdelegate.managedObjectContext

    let entity = NSEntityDescription.entityForName("Person", inManagedObjectContext: managedcontext)

    let person = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedcontext)
    person.setValue(self.nametextfield.text, forKey: "name")

    do
    {
        try managedcontext.save()
        print("SAVED")

    }
    catch let error as NSError
    {
        print("could not save \(error), \(error.userInfo)")
    }

    self.navigationController?.popToRootViewControllerAnimated(true)

}

Here I want the compiler to check the received managed object and update any changes to the database which I am unable to do because SWIFT doesn't accept a managedobject type as condition but I was able to achieve update of database by this concept in ObjC.

And another problem is when I try to compile I get an error as -

failed to call designated initializer on NSManagedObject class 'NSManagedObject'

in the prepereforsegue() method. So how to solve the problem and perform update.

回答1:

This line is wrong because you're trying to create an invalid managed object instance:

var managedobjectt = NSManagedObject()

It should be

var managedobjectt : NSManagedObject?

And when you update you aren't changing the current item if it exists, you're just always creating a new instance. You should

if let person = self.managedobjectt {
    // update (if anything other than below)
} else {
    // create new (insert and set any default values)
}

person.setValue(self.nametextfield.text, forKey: "name")

// save