1

我从远程 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 循环执行保存时的日志:

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 仍然被阻止。

4

1 回答 1

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"];
    }
}];

我想它正在尝试创建和保存太多可能导致崩溃的上下文?

另外,您遇到的崩溃是什么?

于 2013-06-10T11:07:41.530 回答