代码之家  ›  专栏  ›  技术社区  ›  Armanoide

创建nsmanagedobject而不保存[@Example]

  •  1
  • Armanoide  · 技术社区  · 10 年前

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

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

    1 回复  |  直到 8 年前
        1
  •  2
  •   Armanoide    9 年前

    这在IOS7、IOS8上进行了测试 .

    创建tmp NSManagedContext :确保您的 NSManagedObject 当您的上下文将被解除分配时,不会为零。创建一个临时 NSManagedContext 在您的应用程序代理中。

    在文件AppDelegate.swift中

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

    创建NSManagedObject :请致电 customfile.swift tmp和主上下文。主上下文将用于在 被管理对象 .

        // 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 :不幸的是,您无法通过传递主上下文来保存对象。为了避免,您需要复制 被管理对象

    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