保存核心数据的NSOperation内部的ASINetworkQueue错误

时间:2011-12-14 16:44:55

标签: ios asihttprequest nsoperation nsoperationqueue

我想在NSOperation中使用ASINetworkQueue。这很好用,没问题。失败的是保存核心数据。我为此操作设置了一个新的NSManagedObjectContext,就像在文档中告诉它一样。

我认为问题在于我在ASINetworkQueue完成并且调用委托选择器时保存数据。因为在mainThread上调用了委托,所以保存消息失败。

这可能是问题所在,是否有人有解决方案?

1 个答案:

答案 0 :(得分:0)

您正在使用PerformSelectorOnMainThread方法(合并来自新实例化的ManagedObjectContext的更改)?

我在我的操作中做了类似的事情(ctx是我实例化的MOC):

首先注册通知:

// Register context with the notification center
        NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; 

        [nc addObserver:self
               selector:@selector(mergeChanges:) 
                   name:NSManagedObjectContextDidSaveNotification
                 object:ctx];

然后当你需要保存上下文时:

if ([ctx hasChanges]) {
            error = nil;

            // Save the context.
            if (![ctx save:&error])
            {
                // Do something with the error
            }

            // Clear out the scratchpad
            [ctx reset];

        }

然后是与主MOC合并的方法:

- (void)mergeChanges:(NSNotification *)notification
{
    id appDelegate = [[UIApplication sharedApplication] delegate];  

    NSManagedObjectContext *mainContext = [appDelegate managedObjectContext];
    // Merge changes into the main context on the main thread
    [mainContext performSelectorOnMainThread:@selector(mergeChangesFromContextDidSaveNotification:) 
                                  withObject:notification
                               waitUntilDone:NO];
    // NSLog(@"Merged Changes");
}

希望这有帮助

相关问题