嘿,我被同样的问题困扰了好几天,插入时间逐渐增加,在较低的 ipad 中,它也会因内存问题而崩溃。插入 20k 条记录需要 4-5 分钟。后台线程会提高效率吗? ?无论如何我可以优化这个。如果可以,请帮忙。
+(BOOL) addObjectToProfessionalsDBWithDictNSArray*)profArray{
if (!([profArray count]>0 && profArray )) {
return NO;
}
NSManagedObjectContext *thisContext=[self getManagedObjectContext];
for (int i=0; i<[profArray count]; i++) {
NSManagedObject *professionalDBObject = [NSEntityDescription
insertNewObjectForEntityForName"rofessionalsDB"
inManagedObjectContext:thisContext];//initWithDictionarybjectDict]; NSMutableDictionary * objectDict=[profArray objectAtIndex:i];
[professionalDBObject setValue:[objectDict valueForKey"Degree"] forKey"degree"];
[professionalDBObject setValue:[objectDict valueForKey"First_Name"]
// and 10 more values
if(i%500==0){
NSError *error;
NSLog(@"saved rec nu %d",i);
if (![thisContext save:&error]) {
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
return NO;
}
else{
NSLog(@"data saved");
}
[thisContext reset];
}
}
[prefs setInteger:numOfRecords forKey"numberOfRecords"];
NSError *error;
if (![thisContext save:&error]) {
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
return NO;
}
return YES;
}
存储 20k 条记录大约需要 4 分钟。我使用以下代码将其缩短到 8 秒(这真的很棘手!):
+(NSManagedObjectContext*)getInsertContext{
NSManagedObjectContext *thisContext=[[NSManagedObjectContext alloc] init];
AppDelegate *delegate=(AppDelegate*)[[UIApplication sharedApplication] delegate];
NSPersistentStoreCoordinator *coordinator = [delegate persistentStoreCoordinator];
[thisContext setPersistentStoreCoordinator:coordinator];
[thisContext setUndoManager:nil];
return thisContext;
}
我在此上下文中保存的每 1000 条记录,在保存重置后再次获取新上下文:
[thisContext reset];
thisContext=[self getInsertContext];
关于ios Coredata 大集合插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18550873/
欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) | Powered by Discuz! X3.4 |