CoreData写对象慢 [英] CoreData writing objects slow
本文介绍了CoreData写对象慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在从Web服务下载地址列表(15.000个地址)。获取所有地址可能需要800毫秒,而将它们写入CoreData则需要额外的15秒。请在错误之处提供一些建议:
I'm downloading list of addresses from the webservice(15.000 addresses). It took maybe 800ms to get all addresses and additional 15 seconds to write them to CoreData. Please give some advice where I am wrong:
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,并且应该仅在迭代完成后才保存。
Problem was that I was saving managedObjectContext everytime, and it should be saved only when iteration is finished.
仅移动了这一行:
if ([managedObjectContext save:&error] == NO) {
NSAssert(NO, @"Error saving context: %@\n%@", [error localizedDescription], [error userInfo]);
}
以下循环。
这篇关于CoreData写对象慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文