我正在从webservice(15.000地址)下载地址列表。获取所有地址大约需要800ms,并且需要额外的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];
}
答案 0 :(得分:0)
想通了!
问题是我每次都在保存managedObjectContext,只有在迭代完成后才能保存它。
刚刚移动了这一行:
if ([managedObjectContext save:&error] == NO) {
NSAssert(NO, @"Error saving context: %@\n%@", [error localizedDescription], [error userInfo]);
}
下面的循环。