【问题标题】:Save a large number of objects in coredata在coredata中保存大量对象
【发布时间】:2016-02-17 19:26:08
【问题描述】:

我尝试在 coredata 中保存许多对象,但出现此崩溃:

Communications error: <OS_xpc_error: <error: 0x19b354af0> { count = 1, contents =
    "XPCErrorDescription" => <string: 0x19b354e50> { length = 22, contents = "Connection interrupted" }
}>
Message from debugger: Terminated due to memory issue

我使用 MagicalRecord:

[MagicalRecord saveInBackgroundWithBlock:^(NSManagedObjectContext *localContext){
                                    for (int i = 0; i < json.count; i++) {
                                        [Product parseWithData:((NSMutableArray *)json)[i]];
                                    }
                                }];

产品.m

+ (void)parseWithData:(NSDictionary *)dictionary {

        NSString *xml_id = [dictionary[@"XML_ID"] isKindOfClass:[NSString class]] ? dictionary[@"XML_ID"] : @"";

        Product *product = [Product getProductWithXML_id:xml_id];
        if (!product)
            product = [Product MR_createEntity];

        product.xml_id = xml_id;
        product.code = [dictionary[@"Code"] isKindOfClass:[NSString class]] ? dictionary[@"Code"] : @""; 
        ...
}

你能建议我吗,我该如何保存它?

当我将对象循环保存到核心数据时 - 内存增长非常快

【问题讨论】:

    标签: ios core-data magicalrecord


    【解决方案1】:

    这似乎是一个内存问题。

    尝试用

    包围你的for循环的内部部分
    autoreleasepool {
       ...
    }
    

    【讨论】:

      【解决方案2】:

      您需要对获取数据和/或保存数据的方式进行分页。

      分页是指:

      1. 下载前1000个(例如,这取决于内容)
      2. 完成后,保存 1000 条即可
      3. 完成后,获取下一个 1000,再次保存,依此类推。

      您需要知道要获取的数字并在解析方法上使用(如果我没记错的话)SetLimit: 和 SetSkip。跳过跳过第 X 个元素,限制是将下载的最大项目数。 这样,你用 limit 1000 跳过 0,然后用 skip += limit 调用方法,你会得到第二个 1000 块,依此类推。最后一个块显然会小于 1000。

      这样做会大大增加花费的时间,但这可以在后台无缝完成;但它会分布得足够多,需要更少的内存。

      这样做,看看它是否有很大的不同。如果没有,你总是可以减少到 500 而不是 1000,或者完全改变你的架构;也许你现在甚至不需要ALL这些项目!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-10-29
        • 1970-01-01
        • 2018-01-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-07
        相关资源
        最近更新 更多