![](/img/trans.png)
[英]Core data taking time to insert records with fetching entity & set as relationship
[英]Saving 1 million records to core data taking so much time
我正在將CSV中的100萬條記錄保存到核心數據庫中。 保存所有記錄大約需要35分鍾。總之,這可以減少插入時間。 這是我用來插入記錄的代碼:
NSString *resourceFileName = @"npidata_20140209_reduced2";
NSString *pathToFile =[[NSBundle mainBundle] pathForResource: resourceFileName ofType: @"csv"];
NSString* content = [NSString stringWithContentsOfFile:pathToFile
encoding:NSUTF8StringEncoding
error:NULL];
__block int count = 0;
[content enumerateLinesUsingBlock:^(NSString * line,BOOL * stop){NSLog(@“ LINE ==%@”,line);
NSArray *lineComponents=[line componentsSeparatedByString:@","];
if(lineComponents){
float f=[[lineComponents objectAtIndex:0] floatValue];
NSString *strNPI=[lineComponents objectAtIndex:0];
NSString *strProviderLastName=[lineComponents objectAtIndex:1];
NSString *strProviderFirstName=[lineComponents objectAtIndex:2];
NSString *strLicenseNumber=[lineComponents objectAtIndex:6];
NSString *strLicenseState=[lineComponents objectAtIndex:7];
NSManagedObject *object=[NSEntityDescription insertNewObjectForEntityForName:@"AttendeeInformation" inManagedObjectContext:[DataBaseManager sharedInstance].managedObjectContext];
NSString *strFullName = [NSString stringWithFormat:@"%@ %@",strProviderFirstName,strProviderLastName];
[object setValue:strNPI forKey:@"npiNumber"];
[object setValue:strProviderFirstName forKey:@"attendeeFirstName"];
[object setValue:strProviderLastName forKey:@"attendeeLastName"];
[object setValue:strFullName forKey:@"attendeeName"];
[object setValue:strLicenseNumber forKey:@"licnesedNumber"];
[object setValue:strLicenseState forKey:@"stateLicense"];
NSError *error;
count++;
if(count%100==0)
{
if (![[DataBaseManager sharedInstance].managedObjectContext save:&error])
{
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}
[[DataBaseManager sharedInstance].managedObjectContext refreshObject:object mergeChanges:YES];
}
if (count==lineComponents.count)
{
completionHandler();
}
}
}];
您應該運行帶有時間配置文件和核心數據的儀器,以查看瓶頸所在。 這是驗證性能問題的最佳方法。 核心數據可能不是您的問題。
@Desdenova正確。 您需要獲取上下文中的所有記錄,並在末尾至少一次或至少非常大批量地保存一次上下文。 在該API下,sqlite為每個上下文保存執行單獨的事務,這非常昂貴。 如果您將所有操作作為一個事務進行,則速度要快幾個數量級。 在您注釋掉的地方進行測試:
if (![[DataBaseManager sharedInstance].managedObjectContext save:&error])
{
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}
並在循環后添加相同的3行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.