我从远程API获得响应,解析它并在数组中分配,然后循环该数组以保存实体中的每个元素:
for (id element in arrayProduct) {
[MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext) {
Product *product = [Product MR_createInContext:localContext];
([element valueForKey:@"Category Id"] == [NSNull null])?(product.category_id = [NSNumber numberWithInt:-1]):(product.category_id = [NSNumber numberWithInt:[[element valueForKey:@"Category Id"] intValue]]);
}];
}
for循环代码保存到coredata中,但过了一段时间,应用程序崩溃,其余条目被中断,因此不会保存。
这是for循环执行save时的日志:
2013-06-10 11:54:15:461 App[2718:2311] -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:] [Line 42] -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x1fd88c70) NO CHANGES IN ** BACKGROUND SAVING (ROOT) ** CONTEXT - NOT SAVING
2013-06-10 11:54:15:471 App[2718:2311] -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:] [Line 42] -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x1fd88c70) NO CHANGES IN ** BACKGROUND SAVING (ROOT) ** CONTEXT - NOT SAVING
2013-06-10 11:54:16:099 App[2718:135939] -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:] [Line 54] -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x20d96320) → Saving <NSManagedObjectContext (0x20d96320): *** UNNAMED ***> on *** BACKGROUND THREAD *
2013-06-10 11:54:16:101 App[2718:96515] -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:] [Line 54] -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x20d966e0) → Saving <NSManagedObjectContext (0x20d966e0): *** UNNAMED ***> on *** BACKGROUND THREAD *
我正在使用saveWithBlock:
方法,因为其他方法(例如saveInBackgroundWithBlock:
)已弃用。
我几乎没有问题:
- 我在块内部进行for循环,还是应该将块放在for循环中? - 我应该使用什么方法来确保应用程序不会崩溃?是在后台保存数据的方法吗?因为UI在保存时仍然被阻止。
答案 0 :(得分:3)
尝试将其更改为此...
[MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext) {
for (id element in arrayProduct) {
Product *product = [Product MR_createInContext:localContext];
// ([element valueForKey:@"Category Id"] == [NSNull null]) ? (product.category_id = [NSNumber numberWithInt:-1]):(product.category_id = [NSNumber numberWithInt:[[element valueForKey:@"Category Id"] intValue]]);
// that line of code is really hard to read. Changed it to this...
product.category_id = element[@"Category Id"] == [NSNull null] ? @-1 : element[@"Category Id"];
}
}];
我想它正在尝试创建并保存太多可能导致崩溃的上下文?
另外,你遇到的崩溃是什么?