Rashid
Rashid

Reputation: 804

Updating values of a large core data

I am using core data to create about 1800 records. I really dont have a problem with inserting values to core data but when i try to update the existing values it takes ages. This is how i am doing it:

NSManagedObjectContext *context = [self managedObjectContext];
        NSFetchRequest *fetchRequest=[NSFetchRequest fetchRequestWithEntityName:@"Sales"];
        NSArray *Sales=[self.managedObjectContext executeFetchRequest:fetchRequest error:nil];

        for (int i = 0; i<Sales.count; i++)
        {
            [Sales setValue:value1 forKey:@"value1"];
            [Sales setValue:value2 forKey:@"value2"];
            [Sales setValue:value3 forKey:@"value3"];
            [Sales setValue:value4 forKey:@"value4"];
            [Sales setValue:value5 forKey:@"value5"];
            [context save:nil];
        }

Upvotes: 0

Views: 47

Answers (1)

pbasdf
pbasdf

Reputation: 21536

You are invoking setValue:forKey: on the array Sales. That automatically invokes that method on every member of the array. From the documentation:

Invokes setValue:forKey: on each of the array's items using the specified value and key.

But you have then wrapped it in a for loop that repeats it ~1800 times. Either remove the for loop, or invoke setValue:forKey: directly on each member of the array, eg.

        [Sales[i] setValue:value1 forKey:@"value1"];

If you do the latter, move the save outside the for loop, so the context is saved once at the end rather than after each and every item.

So either:

    [Sales setValue:value1 forKey:@"value1"];
    [Sales setValue:value2 forKey:@"value2"];
    [Sales setValue:value3 forKey:@"value3"];
    [Sales setValue:value4 forKey:@"value4"];
    [Sales setValue:value5 forKey:@"value5"];
    [context save:nil];

or

    for (int i = 0; i<Sales.count; i++)
    {
        [Sales[i] setValue:value1 forKey:@"value1"];
        [Sales[i] setValue:value2 forKey:@"value2"];
        [Sales[i] setValue:value3 forKey:@"value3"];
        [Sales[i] setValue:value4 forKey:@"value4"];
        [Sales[i] setValue:value5 forKey:@"value5"];
    }
    [context save:nil];

Upvotes: 1

Related Questions