iphone - 如何使用 Core Data 加快将新对象插入实体的速度

标签 iphone objective-c ios core-data

这是我的代码,它获取一些 JSON 数据并将其插入核心数据室实体:

for (NSDictionary *room in rooms)
    {
        NSDictionary *thisroom = [room objectForKey:@"room"];
        NSString *roomidstring = [thisroom objectForKey:@"roomid"];
        int roomid = [roomidstring intValue];
        NSString *roomname = [thisroom objectForKey:@"roomname"];
        NSString *buildingidstring = [thisroom objectForKey:@"buildingid"];
        int buildingid = [buildingidstring intValue];

        // import into database
        NSManagedObject *roomInfo = [NSEntityDescription insertNewObjectForEntityForName:@"room" inManagedObjectContext:context];
        [roomInfo setValue:[NSNumber numberWithInteger:roomid] forKey:@"roomid"];
        [roomInfo setValue:roomname forKey:@"roomname"];
        [roomInfo setValue:[NSNumber numberWithInteger:buildingid] forKey:@"buildingid"];
         if (![context save:&error]) {
            NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
        }
    }

插入大约 900 个对象时速度非常慢。有什么方法可以提高效率和/或加快速度吗?

谢谢!

最佳答案

是的,在完成循环之前不要保存,或者如果内存有问题,请分批保存。保存操作非常昂贵,因此您应该避免在像这样的紧密循环中经常保存。

for (NSDictionary *room in rooms)
{
    NSDictionary *thisroom = [room objectForKey:@"room"];
    NSString *roomidstring = [thisroom objectForKey:@"roomid"];
    int roomid = [roomidstring intValue];
    NSString *roomname = [thisroom objectForKey:@"roomname"];
    NSString *buildingidstring = [thisroom objectForKey:@"buildingid"];
    int buildingid = [buildingidstring intValue];

    // import into database
    NSManagedObject *roomInfo = [NSEntityDescription insertNewObjectForEntityForName:@"room" inManagedObjectContext:context];
    [roomInfo setValue:[NSNumber numberWithInteger:roomid] forKey:@"roomid"];
    [roomInfo setValue:roomname forKey:@"roomname"];
    [roomInfo setValue:[NSNumber numberWithInteger:buildingid] forKey:@"buildingid"];
}


if (![context save:&error]) {
     NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}

关于iphone - 如何使用 Core Data 加快将新对象插入实体的速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7335509/

相关文章:

iphone - 在 Xcode 4 和 iOS 4 中定义成员和属性

iphone - Cydia 和 AppStore 中的 iOS 应用

iphone - 将 iPhone 设备连接到 Xcode 项目

ios - 即使在 CLLocationManager 上明确调用 stopUpdatingLocation 后,状态栏上的位置服务指示器仍然出现

UITableView 数组返回 nil

iphone - 重新启动非空函数

ios - 在 iPhone 上加载数据文件?

ios - 如何预览在 .xib 文件中以编程方式创建的项目?

iphone - 我是否仍需要在带有 ARC 的 viewDidUnload 中将 IBOutlet 属性设置为 null

ios - iBeacon可以检测配件的接近程度(背景中的应用程序)