Objective c Coredata:保存大量数据时出现性能问题
我想在初始启动时用CSV文件中的一些数据填充我的应用程序数据库(50000个条目)。但是我遇到了性能问题…现在速度太慢了,在模拟器中需要2-3分钟。我的上下文层次结构如下所示: parentContext(独立线程) 上下文(主线程) importContext(独立线程) 守则:Objective c Coredata:保存大量数据时出现性能问题,objective-c,multithreading,core-data,Objective C,Multithreading,Core Data,我想在初始启动时用CSV文件中的一些数据填充我的应用程序数据库(50000个条目)。但是我遇到了性能问题…现在速度太慢了,在模拟器中需要2-3分钟。我的上下文层次结构如下所示: parentContext(独立线程) 上下文(主线程) importContext(独立线程) 守则: for (NSString *row in rows){ columns = [row componentsSeparatedByString:@";"]; //Ste
for (NSString *row in rows){
columns = [row componentsSeparatedByString:@";"];
//Step 1
Airport *newAirport = [Airport addAirportWithIcaoCode: [columns[0] stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]]
name:columns[1]
latitude:[columns[2] doubleValue]
longitude:[columns[3] doubleValue]
elevation:[columns[4] doubleValue]
continent:columns[5]
country:columns[6]
andIataCode:columns[7]
inManagedObjectContext:self.cdh.importContext];
rowCounter++;
//Increment progress
dispatch_async(dispatch_get_main_queue(), ^{
[progress setProgress:rowCounter/totalRows animated:YES];
[progress setNeedsDisplay];
});
// STEP 2: Save new objects to the parent context (context).
//if(fmodf(rowCounter, batchSize)== 0) {
NSError *error;
if (![self.cdh.importContext save:&error]) {
NSLog(@"error saving %@", error);
}
//}
// STEP 3: Turn objects into faults to save memory
[self.cdh.importContext refreshObject:newAirport mergeChanges:NO];
}
如果我在步骤2中为batch size 2000激活带模If,那么当然只有每2000个条目被保存一次,那么性能会很快。但就像这样,它是超慢的,我想知道为什么?我的导入上下文在一个单独的线程中,但仍然非常滞后…通常,在处理完所有条目后,只需发出一个
保存
。你不需要经常保存这些。只需在for
循环之后执行即可。我看到您试图通过每次将对象转换为故障来节省内存,因此这可能需要保存(以前没有尝试过)
我建议您改用@autoreleasepool
,让系统决定在何处保存内存:
for (NSString *row in rows) {
@autoreleasepool {
// Just STEP 1 here
...
}
}
NSError *error;
if (![self.cdh.importContext save:&error]) {
NSLog(@"error saving %@", error);
}
它总是同一个CSV文件吗?将初始持久存储放在应用程序中,并在初始启动时复制到适当的位置。