gpt4 book ai didi

ios - CoreData写对象慢

转载 作者:行者123 更新时间:2023-11-29 11:58:12 24 4
gpt4 key购买 nike

我正在从网络服务下载地址列表(15.000 个地址)。获取所有地址可能需要 800 毫秒,另外还需要 15 秒才能将它们写入 CoreData。不对的地方请指教:

AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *managedObjectContext = delegate.managedObjectContext;
for (NSDictionary *dict in addresses) {
[self saveAddressesToCoreDataWithDictionary:dict andManagedObject:managedObjectContext];
}
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"alreadyDownloaded"];

和方法:

-(void)saveAddressesToCoreDataWithDictionary:(NSDictionary *)dict andManagedObject:(NSManagedObjectContext *)managedObject
{

NSManagedObject *address;
address = [NSEntityDescription insertNewObjectForEntityForName:@"Address" inManagedObjectContext:managedObject];

[address setValue:[[dict objectForKey:@"lat"] stringValue] forKey:@"lat"];
[address setValue:[[dict objectForKey:@"lon"] stringValue] forKey:@"lon"];
[address setValue:[dict objectForKey:@"addressLong"] forKey:@"addressLong"];
[address setValue:[dict objectForKey:@"addressShort"] forKey:@"addressShort"];
NSError *error;
[managedObject save:&error];

}

最佳答案

想通了!

问题是我每次都在保存 managedObjectContext,它应该只在迭代完成时保存。

刚刚移动了这一行:

if ([managedObjectContext save:&error] == NO) {
NSAssert(NO, @"Error saving context: %@\n%@", [error localizedDescription], [error userInfo]);
}

下面的for循环。

关于ios - CoreData写对象慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38205534/

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