如何在 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];
}
上面的代码只是覆盖了之前的条目。插入下一行的正确步骤是什么?
最佳答案
您需要为每个核心数据管理对象创建一个新的插入语句。否则,您只是在编辑现有的 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];
}
关于ios - 添加多行/连续行 - 在 Coredata 中填充数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14164403/