gpt4 book ai didi

ios Coredata大集插入

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:45:58 24 4
gpt4 key购买 nike

嘿,我被同样的问题困扰了好几天,插入时间逐渐增加,在较低的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com