如何在核心数据和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];
}
上面的代码刚刚写完前一个条目。插入下一行的正确程序是什么?
答案 0 :(得分: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];
}