作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
嘿,我被同样的问题困扰了好几天,插入时间逐渐增加,在较低的 ipad 中它也会因内存问题而崩溃。插入 20k 记录需要 4-5 分钟。后台线程会提高效率吗? ?无论如何我可以优化这个。如果可以,请帮忙。
+(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;
最佳答案
存储 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/
我是一名优秀的程序员,十分优秀!