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

iOS CoreData批量插入?

  •  23
  • james  · 技术社区  · 15 年前

    在我的iPhone应用程序中,我需要在核心数据中插入~2000条记录,然后用户才能使用该应用程序的任何功能。我正在从本地JSON文件将记录加载到coredata中。此过程耗时较长(2.5分钟以上),但只需执行一次(或每隔10个应用程序打开一次以获取更新的数据)。

    核心数据是否有批量插入?如何加快插入过程?

    如果我不能使用核心数据加速,还有什么其他推荐的选项?

    3 回复  |  直到 9 年前
        1
  •  28
  •   Matt user129975    10 年前

    查看 Efficiently Importing Data 核心数据编程指南的章节。

    我现在和你有同样的问题,只是我要插入10000个对象,大约需要30秒,这对我来说仍然很慢。我正在对插入到上下文中的每1000个托管对象执行[ManagedObjectContext Save](换句话说,我的批处理大小为1000)。我尝试了30种不同的批量大小(从1到10000),在我的例子中,1000似乎是最佳值。

        2
  •  5
  •   Community Mohan Dere    9 年前

    我在找答案 a similar question 当我遇到这个的时候。@弗拉基米尔米特罗维奇的回答在当时很有帮助,因为我知道我不应该每次都保存上下文,但我也在寻找一些示例代码。

    现在我有了它,我将提供下面的代码,以便其他人可以看到执行批插入时的情况。

    // set up a managed object context just for the insert. This is in addition to the managed object context you may have in your App Delegate.
    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. Your implementation may vary.
    
            autoreleasepool { // auto release objects after the batch save
    
                let array: Array<MyManagedObject>? = getNextBatchOfObjects() // The MyManagedObject class is your entity class, probably named the same as MyEntity
                if array == nil { break } // there are no more objects to insert so stop looping through the batches
    
                // insert new entity object
                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()
        }
    }
    
        3
  •  0
  •   Abhishek Thapliyal    9 年前

    目标-C

    @suragch anwser版本

    NSManagedObjectContext * MOC = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
    MOC.persistentStoreCoordinator = YOURDB.persistentStoreCoordinator;
    [MOC performBlock:^{ 
       // DO YOUR OPERATION
     }];