Where should NSManagedObjectContext be created?

前端 未结 2 892
天命终不由人
天命终不由人 2021-01-20 02:46

I\'ve recently been learning about Core Data and specifically how to do inserts with a large number of objects. After learning how to do this and solving a memory leak probl

2条回答
  •  情书的邮戳
    2021-01-20 03:06

    This is a supplemental answer to @JodyHagins' answer. I am providing a Swift implementation of the pseudocode that was provided there.

    let managedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.PrivateQueueConcurrencyType)
    managedObjectContext.persistentStoreCoordinator = (UIApplication.sharedApplication().delegate as! AppDelegate).persistentStoreCoordinator // or wherever your coordinator is
    
    managedObjectContext.performBlock { // runs asynchronously
    
        while(true) { // loop through each batch of inserts
    
            autoreleasepool {
                let array: Array? = getNextBatchOfObjects()
                if array == nil { break }
                for item in array! {
                    let newEntityObject = NSEntityDescription.insertNewObjectForEntityForName("MyEntity", inManagedObjectContext: managedObjectContext) as! MyManagedObject
                    newObject.attribute1 = item.whatever
                    newObject.attribute2 = item.whoever
                    newObject.attribute3 = item.whenever
                }
            }
    
            // only save once per batch insert
            do {
                try managedObjectContext.save()
            } catch {
                print(error)
            }
    
            managedObjectContext.reset()
        }
    }
    

    These are some more resources that helped me to further understand how the Core Data stack works:

    • Core Data Stack in Swift – Demystified
    • My Core Data Stack

提交回复
热议问题