在不保存的情况下创建 nsmanagedobject [@Example]

Create nsmanagedobject without saving [@Example]

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

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

这是在 IOS7、IOS8 上测试的。

Create 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