创建nsmanagedobject而不保存[@Example]

时间:2015-02-11 15:50:13

标签: ios nsmanagedobject nsmanagedobjectcontext

我想创建NSManagedObject但不立即保存。

我在哪里可以找到创建临时NSmanagedObject的示例?

1 个答案:

答案 0 :(得分:2)

这是在IOS7,IOS8 上测试的。

创建tmp NSManagedContext :为了确保在您的上下文被dealloc时NSManagedObject不会为nil,请在您的应用程序委托中创建一个临时NSManagedContext

在文件AppDelegate.swift

import UIKit
import CoreData

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    private(set) var tmpContext : NSManagedObjectContext = NSManagedObjectContext()

    ....

}

创建NSManagedObject :在customfile.swift tmp和主要上下文中调用。主要上下文将用于在NSManagedObject

的实例中访问您的模型
    // CONTEXT
    let tmpContext     = (UIApplication.sharedApplication().delegate as AppDelegate).tmpContext
    let managedContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext!

    // ENTITY
    let entity         = NSEntityDescription.entityForName("MY_ENTITY_NAME", inManagedObjectContext: managedContext)
    let obj            = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: tmpContext)

保存您的NSManagedObject :遗憾的是,您无法通过传递主要上下文来保存对象。为避免这种情况,您需要复制所有NSManagedObject

var error : NSError?

// CREATE YOUR NSManagedObject
    let managedContext     = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext!
    let entity             = NSEntityDescription.entityForName("MY_ENTITY_NAME", inManagedObjectContext: managedContext)
    let newObj             = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext)


// COLLECT ALL VALUE SET OF YOUR OBJ            
    let keysObj            = (obj.entity.attributesByName as NSDictionary).allKeys
    let dictObj            = track.dictionaryWithValuesForKeys(keysObj)


 newObj.setValuesForKeysWithDictionary(dictObj)

 // SAVE ALL

 managedContext.processPendingChanges()
 managedContext.insertObject(newObj)
 managedContext.save(&error) // dont forget to check