Reputation: 6892
I have a very simple class that I am using to try learn core image based on master detail view template. The data is saving ok when I add a new item. but when I delete it the context says that there is nothing to change.
Any ideas on how to correctly get it to save the updated object class to coreimage after I delete an event.
Here are the class variables:
import UIKit
import CoreData
class MasterViewController: UITableViewController {
var objects: [Event]!
Here are the methods that handle the adding and deleting from the Tableview:
func insertNewObject(sender: AnyObject) { //Triggered by add button in top menu
objects.insert(Event(context: sharedContext), atIndex: 0)
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
CoreDataStackManager.sharedInstance().saveContext()
}
//Delete method is done via editing:
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
objects.removeAtIndex(indexPath.row)
CoreDataStackManager.sharedInstance().saveContext() // This doesn't result in CoreData thinking that the main object has changed
println(objects.count)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
The Event model is done as an NSManaged Object:
import Foundation
import CoreData
@objc(Event)
class Event : NSManagedObject {
@NSManaged var timeStamp: NSDate
override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) {
super.init(entity: entity, insertIntoManagedObjectContext: context)
}
init(context: NSManagedObjectContext) {
let entity = NSEntityDescription.entityForName("Event", inManagedObjectContext: context)!
super.init(entity: entity, insertIntoManagedObjectContext: context)
timeStamp = NSDate()
}
}
Any help would be welcome.
Upvotes: 0
Views: 118
Reputation: 539765
You delete the object from your objects
array, but not from the managed
object context. You'll have to add
sharedContext.deleteObject(objects[indexPath.row])
(If you were using a NSFetchedResultsController
as a table view data source then this would be the only necessary action, since the table view
would then be updated automatically from the fetched results controller
delegate methods.)
Upvotes: 2