我有一个非常简单的类,我正在使用它来尝试学习基于主细节 View 模板的核心图像。当我添加新项目时,数据保存正常。但是当我删除它时,上下文说没有什么可以改变的。
关于如何在我删除事件后正确获取它以将更新的对象类保存到 coreimage 的任何想法。
这里是类变量:
import UIKit
import CoreData
class MasterViewController: UITableViewController {
var objects: [Event]!
以下是处理从 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.
}
}
事件模型作为 NSManaged 对象完成:
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()
}
欢迎任何帮助。
最佳答案
您从 objects
数组中删除对象,但不从托管对象中删除
对象上下文。你必须添加
sharedContext.deleteObject(objects[indexPath.row])
(如果您使用 NSFetchedResultsController
作为 TableView 数据源,那么这将是唯一必要的操作,因为 TableView
然后将从获取的结果 Controller 自动更新
委托(delegate)方法。)
关于ios - 无法获取 CoreData 以删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32092959/