Insert multiple objects using CoreData
I have a situation where I want to pre populate a CoreData DB with a few entries. As this is done at runtime as a few things are detected then I need to do this in code.
I have an开发者_如何学Python issue with this code where it only inserts the second one....
Event *event = (Event *)[NSEntityDescription insertNewObjectForEntityForName:@"Event" inManagedObjectContext:managedObjectContext];
[event setLat:[NSNumber numberWithDouble:52.25]];
[event setLon:[NSNumber numberWithDouble:4.75]];
[event setLatspan:[NSNumber numberWithDouble:0.7]];
[event setLonspan:[NSNumber numberWithDouble:0.88]];
[event setName:@"Test, 1"];
// Commit the change.
NSError *error;
if (![managedObjectContext save:&error]) {
NSLog(@"%@",[error description]);
}
[event setLat:[NSNumber numberWithDouble:53.25]];
[event setLon:[NSNumber numberWithDouble:56.75]];
[event setLatspan:[NSNumber numberWithDouble:0.7]];
[event setLonspan:[NSNumber numberWithDouble:0.88]];
[event setName:@"Test 2"];
if (![managedObjectContext save:&error]) {
NSLog(@"%@",[error description]);
}
The problem is that you call insertNewObjectForEntityForName:inManagedObjectContext:
only once, and use the same object twice. Thus only one item is being inserted, its existing attributes modified, then the changes to the same object saved.
You need to call insertNewObjectForEntityForName:inManagedObjectContext:
again on the same event
variable for each subsequent item, after saving it (the managed objects produced here are all autoreleased):
event = (Event *)[NSEntityDescription insertNewObjectForEntityForName:@"Event" inManagedObjectContext:managedObjectContext];
[event setLat:[NSNumber numberWithDouble:53.25]];
[event setLon:[NSNumber numberWithDouble:56.75]];
[event setLatspan:[NSNumber numberWithDouble:0.7]];
[event setLonspan:[NSNumber numberWithDouble:0.88]];
[event setName:@"Test 2"];
if (![managedObjectContext save:&error]) {
NSLog(@"%@",[error description]);
}
精彩评论