使用Core Data插入多个对象

时间:2011-03-07 08:19:51

标签: iphone objective-c core-data

我有一种情况,我想用一些条目预先填充CoreData DB。由于这是在运行时完成的,因为检测到一些事情,所以我需要在代码中执行此操作。

我对此代码有一个问题,它只插入第二个....

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

1 个答案:

答案 0 :(得分:12)

问题是你只调用insertNewObjectForEntityForName:inManagedObjectContext:一次,并使用同一个对象两次。因此,只插入一个项目,其现有属性已修改,然后保存对同一对象的更改。

在保存后,您需要在每个后续项目的同一个insertNewObjectForEntityForName:inManagedObjectContext:变量上再次调用event(此处生成的托管对象全部自动释放):

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