我正在将核心数据实体迁移到Realm。该实体中可能有超过200万条记录,因此我希望尽可能高效地执行此操作。
迁移将分批处理大约10000条记录,以下是我正在使用的代码:
/// We're in a loop
/// Get the 10000 records out of Core Data
[realm beginWriteTransaction];
// samples is an NSArray of NSManagedObjects
NSInteger numberOfSamples = samples.count;
for (NSInteger i = 0; i < numberOfSamples; i++)
{
// WeightSample is an NSManagedObject
WeightSample *sample = samples[i];
//Diagnostic is an RLMObject
Diagnostic *weightSample = [Diagnostic new];
///
/// transfer data from WeightSample to Diagnostic
///
[realm addObject:weightSample];
// Remove the old sample from Core Data
[context deleteObject:sample];
}
[realm commitWriteTransaction];
/// Start over at the top of the loop
我在执行
[context deleteObject:sample]
块内的beginWriteTransaction-commitWriteTransaction
时会遇到任何问题吗?根据我神秘的tweet @Realm及其回复,我的假设是“否,但是我会阻止更长的时间”。
我可以将其卸载到另一个线程,对吗?
最佳答案
我已经对Realm做过类似的事情,但就我而言,我发现在迁移完成后仅删除所有核心数据sqlite文件是最快/最有效的。我假设迁移完成后就不需要核心数据存储,因此,这就是我的处理方法。
/// We're in a loop
/// Get the 10000 records out of Core Data
[realm beginWriteTransaction];
// samples is an NSArray of NSManagedObjects
// WeightSample is an NSManagedObject
for (WeightSample *sample in samples)
{
//Diagnostic is an RLMObject
Diagnostic *weightSample = [Diagnostic new];
///
/// transfer data from WeightSample to Diagnostic
///
[realm addObject:weightSample];
}
[realm commitWriteTransaction];
/// Start over at the top of the loop
/// After all the data has been transferred to realm, delete all core-data sqlite files using NSFileManager API.