添加多个/顺序行 - 在Coredata中填充DB

llB*_*tll 3 core-data nsmanagedobjectcontext ios

如何在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];
}
Run Code Online (Sandbox Code Playgroud)

刚刚结束的代码写入了上一个条目.插入下一行的正确程序是什么?

ama*_*ttn 6

您需要为每个核心数据管理对象创建一个新的insert语句.否则,您只编辑现有的MO.此外,您只需要在结束时保存一次.

-(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];
}
Run Code Online (Sandbox Code Playgroud)