Search code examples
iosnsmanagedobjectnsmanagedobjectcontext

Create nsmanagedobject without saving [@Example]


I want to create a NSManagedObject but not save immediately.

Where can I find an example of creating a temporary NSmanagedObject?


Solution

  • This was tested On IOS7, IOS8.

    Create tmp NSManagedContext : To make sure that your NSManagedObject will not be nil when your context will be dealloc create a temporary NSManagedContext in your Application delegate.

    in file AppDelegate.swift

    import UIKit
    import CoreData
    
    @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate {
    
        private(set) var tmpContext : NSManagedObjectContext = NSManagedObjectContext()
    
        ....
    
    }
    

    Create a NSManagedObject : Call in your customfile.swift tmp and the main context. The main context will be use to reach your model at the instance of your 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)
    

    Save Your NSManagedObject : unfortunately you cannot save your object by passing the main context. To avoid, you will need to copy all your 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