1

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"];

And method:

-(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];

}
Stefan
  • 1,283
  • 15
  • 33
  • If I remember correctly, you could convert all your `NSDictionary` object into a `Address` Entity (`NSManagedObject`), and after save them all (with the `NSManagedObjectContext`) instead of saving them one by one that could take more time. You may get more info by looking for "Core Data Save Batch", like there: http://stackoverflow.com/questions/4145888/ios-coredata-batch-insert – Larme Jul 05 '16 at 14:10
  • @Larme any hints? I don't have so much experience with cd. – Stefan Jul 05 '16 at 14:23
  • https://developer.apple.com/library/prerelease/content/documentation/Cocoa/Conceptual/CoreData/CreatingObjects.html#//apple_ref/doc/uid/TP40001075-CH5-SW4 You used the `save:` method from `NSManagedObject` where you could use the `save:` method from `NSManagedObjectContext`. Create all your `NSManagedObject`, then perform the save with the context. – Larme Jul 05 '16 at 14:28
  • Yes, yes and yes!!! I saved moc everytime I iterated through this array, and it should only save once it finished itteration. – Stefan Jul 05 '16 at 14:36

1 Answers1

1

Figured out!

Problem was that I was saving managedObjectContext everytime, and it should be saved only when iteration is finished.

Just moved this line:

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

below for loop.

Stefan
  • 1,283
  • 15
  • 33