3

如何在 coredata 和 xcode 中插入多个/连续的新行?

-(void)LoadDB{
    CoreDataAppDelegate *appdelegate = [[UIApplication sharedApplication]delegate];
    context = [appdelegate  managedObjectContext];

    NSManagedObject *newPref;        
    newPref = [NSEntityDescription
           insertNewObjectForEntityForName:NSStringFromClass([Preference class])
           inManagedObjectContext:context];
    NSError *error;

    [newPref setValue: @"0" forKey:@"pid"];      
    [context save:&error];

    [newPref setValue: @"1" forKey:@"pid"];    
    [context save:&error];
}

上面的代码只是重写了前一个条目。插入下一行的正确程序是什么?

4

1 回答 1

7

You need a new insert statement for each core data managed object. Otherwise you are only editing the existing MO. Also, you only need to save once at the end.

-(void)LoadDB{
    CoreDataAppDelegate *appdelegate = [[UIApplication sharedApplication]delegate];
    context = [appdelegate  managedObjectContext];

    NSManagedObject *newPref;
    NSError *error;

    newPref = [NSEntityDescription
               insertNewObjectForEntityForName:NSStringFromClass([Preference class])
               inManagedObjectContext:context];
    [newPref setValue: @"0" forKey:@"pid"];    


    newPref = [NSEntityDescription
               insertNewObjectForEntityForName:NSStringFromClass([Preference class])
               inManagedObjectContext:context];
    [newPref setValue: @"1" forKey:@"pid"];    

    // only save once at the end.
    [context save:&error];
}
于 2013-01-04T20:29:04.047 回答