本文介绍了ios Coredata大集插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
hey我卡住了同样的问题,天,插入的时间逐渐增加,在较低的ipads它也崩溃与内存问题。要插入20k记录需要4-5分钟。将后台线程提高效率。 ?有没有反正我可以优化这。如果可以,请帮忙。
hey i am stuck with the same problem for days , time for insert increases gradually and in lower ipads it also crashes with memory problem .To insert 20k records it takes 4-5 minutes.Will background thread improve efficieny. ? Is there anyway i can optimize this. Please help out if you can.
+(BOOL) addObjectToProfessionalsDBWithDict:(NSArray*)profArray{
if (!([profArray count]>0 && profArray )) {
return NO;
}
NSManagedObjectContext *thisContext=[self getManagedObjectContext];
for (int i=0; i<[profArray count]; i++) {
NSManagedObject *professionalDBObject = [NSEntityDescription
insertNewObjectForEntityForName:@"ProfessionalsDB"
inManagedObjectContext:thisContext];//initWithDictionary:objectDict]; 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;
}
推荐答案
大约需要4分钟才能存储20k条记录。我使用以下代码将它降低到8秒(它真的很棘手!):
It was taking around 4 minutes to store 20k records. I have brought it down to 8seconds(it was really tricky!) with the following code:
+(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;
}
保存在此上下文中,保存重置后再次获取新的上下文:
on every 1000 records i save in this context, after saving reset and get a new context again:
[thisContext reset];
thisContext=[self getInsertContext];
这篇关于ios Coredata大集插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!