如何通过swift中的NSManagedObjectContext更新核心日期中的对象?

时间:2014-12-26 04:10:35

标签: ios core-data

我从核心数据中获取对象数组:

lazy var managedObjectContext : NSManagedObjectContext? = {
        let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
        if let managedObjectContext = appDelegate.managedObjectContext {
            return managedObjectContext
        }
        else {
            return nil}
        }()
var tests=[Test]()
func fetchLog() {
        let fetchRequest = NSFetchRequest(entityName: "Test")
        if let fetchResults = managedObjectContext!.executeFetchRequest(fetchRequest, error: nil) as? [Test] {
            tests = fetchResults
        }

然后托盘更新它:

 managedObjectContext?.updatedObjects(tests[atRow] as NSManagedObject)

但是得到错误:'(NSManagedObject) - > $ T5'与' NSSet'

不同

怎么了?

1 个答案:

答案 0 :(得分:1)

NSManagedObject已在NSManagedObjectContext(MOC)中注册。要更新它,请致电MOC的save()

像这样:

let aTest = test[atRow] as Test
// update through properties like aTest.id = 2
...

// and save
var error: NSError?
if managedObjectContext!.save(&error) {
    println("saved successfully")
} else {
    println("failed to save")
    if let saveError = error {
        println("error=\(saveError.localizedDescription)")
    }
}