Search code examples
iosswiftcore-datansmanagedobject

How to Update existing objects in Core Data?


I'd like to update an object in Core Data. This is my code:

var detailTaskModel: TaskModel!
detailTaskModel.date = dateFromDP         //update value

let appDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
appDelegate.saveContext()

I'm using a NSFetchedResultsController and Swift.

Update:

var fetchedResultsController: NSFetchedResultsController = NSFetchedResultsController()

My func for loading the CoreData data:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    var cell: TaskCell = tableView.dequeueReusableCellWithIdentifier("myCell") as TaskCell

    let thisTask = fetchedResultsController.objectAtIndexPath(indexPath) as TaskModel
    cell.textLabel?.text = thisTask.task
    return cell
}

Saving CoreData:

let appDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
let entityDescription = NSEntityDescription.entityForName("TaskModel", inManagedObjectContext: managedObjectContext!)
let task = TaskModel(entity: entityDescription!, insertIntoManagedObjectContext: managedObjectContext!)
task.task = labelText

Solution

  • You simply update any property of Core data object and call save on NSManagedObjectContext. You can also check for any changes with hasChanges method.

     managedObject.setValue("newValue", forKey: "propertyName") 
    

    Update your object like above or direct call assignment and do the following

    if let moc = self.managedObjectContext {
       var error: NSError? = nil
       if moc.hasChanges {
           !moc.save(&error)
       }
    }