ios - 添加多行/连续行 - 在 Coredata 中填充数据库

标签 ios core-data nsmanagedobjectcontext

如何在 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/

相关文章:

swift - NSManagedObject 子类重复声明

ios - NSFetchedResultsController 是否观察持久存储的所有更改?

ios - 使用 NSURL 检索托管对象 ID

ios - 导航栏不透明

ios - iPhone 应用程序的生命周期是什么?

ios - 使用地理位置查找 ios 设备当前位置

ios - 如何在不通知 NSFetchedResultsController 的情况下更新 NSManagedObject 或 NSManagedObjectContext

ios - 使用 coredata 快速处理临时值的最佳方法

ios - 核心数据仅保存到一个实体

ios - managedObjectContext 无法识别的选择器发送到实例