How to update existing object in core data ? [Swift]

后端 未结 3 1057
广开言路
广开言路 2020-12-21 08:49

I have preloaded data from a .csv file into coredata. I am fetching the data in the following way

var places:[Places] = []

in viewDi

3条回答
  •  春和景丽
    2020-12-21 08:56

    Your current code is:

    if let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext {
    
                let place : Places = Places()
                place.isFavourite = cell.isFavouriteLabel.text
                 do{
                    try managedObjectContext.save()
                } catch let error as NSError{
                    print(error)
    
                }
              }
    

    That would create a new place (if it worked), but you need to update an existing one.

    You have the places returned from managedObjectContext.executeFetchRequest.

    So you need to get something like places[index_of_the_cell_in_question].isFavourite = cell.isFavouriteLabel.text

    and then managedObjectContext.save().

提交回复
热议问题