嘿,我被同一个问题困了几天,插入的时间逐渐增加,而在较低的ipads中,它也与内存问题崩溃,.To插入20k记录,它需要4-5 minutes.Will背景线程来提高效率。?不管怎么说,我可以优化这个。如果可以的话请帮忙。
+(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;}
发布于 2013-11-07 10:06:49
存储2万张唱片大约需要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];发布于 2013-08-31 19:15:58
在启动时将种子数据插入数据库原则上没有问题。复制现成的核心数据数据库当然是快速的,但准备和更新也很麻烦。
以下是一些想法:
1)重写for循环,以便遍历批处理,并让内部循环遍历记录。将两个循环封装到单独的@autoreleasepool括号中。
2)在从字典中检索值时,考虑将valueForKey更改为objectForKey。差别是微妙的,但很重要。
3)澄清你的thisContext来自哪里。是应用程序的主上下文还是子上下文。在后一种情况下,保存实际上不会写入数据库,直到父保存。
4)考虑托管对象上下文的performBlock API,它为您提供了额外的线程和内存隔离。
发布于 2013-08-31 17:40:43
您应该附带已经在包中创建的这个DB。
https://stackoverflow.com/questions/18550873
复制相似问题