Stefan
Stefan

Reputation: 1335

CoreData writing objects slow

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

}

Upvotes: 1

Views: 454

Answers (1)

Stefan
Stefan

Reputation: 1335

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.

Upvotes: 1

Related Questions