在coredata中保存大量对象
Save a large number of objects in coredata
我尝试在 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]];
}
}];
Product.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"] : @"";
...
}
你能建议我吗,我该如何保存?
当我将对象循环保存到核心数据时 - 内存增长非常快
好像是内存问题。
尝试用
包围for
循环的内部
autoreleasepool {
...
}
您需要对获取数据的方式进行分页and/or保存它。
分页,我的意思是:
- 下载前1000个(例如,具体取决于内容)
- 完成后,保存您刚刚使用的 1000 个
- 完成后,获取下一个 1000,再次保存,依此类推。
您需要知道要获取的数字并使用(如果我没记错的话)解析方法上的 SetLimit: 和 SetSkip。 skip 跳过第 X 个元素,限制是将下载的项目的最大数量。
这样,您跳过 0 和 limit 1000,然后调用 skip += limit 的方法,您将获得第二个 1000 块,依此类推。最后一个块显然会小于 1000。
这样做会大大增加所花费的时间,但这可以在后台无缝完成;但它会分散得足够多,需要更少的内存。
去做,看看它是否有很大的不同。如果不是,你总是可以减少到 500 而不是 1000,或者完全改变你的架构;也许您现在甚至不需要 所有 项!
我尝试在 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]];
}
}];
Product.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"] : @"";
...
}
你能建议我吗,我该如何保存?
当我将对象循环保存到核心数据时 - 内存增长非常快
好像是内存问题。
尝试用
包围for
循环的内部
autoreleasepool {
...
}
您需要对获取数据的方式进行分页and/or保存它。
分页,我的意思是:
- 下载前1000个(例如,具体取决于内容)
- 完成后,保存您刚刚使用的 1000 个
- 完成后,获取下一个 1000,再次保存,依此类推。
您需要知道要获取的数字并使用(如果我没记错的话)解析方法上的 SetLimit: 和 SetSkip。 skip 跳过第 X 个元素,限制是将下载的项目的最大数量。 这样,您跳过 0 和 limit 1000,然后调用 skip += limit 的方法,您将获得第二个 1000 块,依此类推。最后一个块显然会小于 1000。
这样做会大大增加所花费的时间,但这可以在后台无缝完成;但它会分散得足够多,需要更少的内存。
去做,看看它是否有很大的不同。如果不是,你总是可以减少到 500 而不是 1000,或者完全改变你的架构;也许您现在甚至不需要 所有 项!