核心数据和并发,2解决方案,我应该使用哪种方式?

时间:2011-06-01 14:10:21

标签: core-data concurrency

我从服务器获取一些数据,我需要解析它。然后,一些解析结果可能需要使用核心数据进行保存。

现在这是我的代码:

- (void)receiveSomeMessage:(NSString *)message
{
    [self performSelectorInBackground:@selector(parseMessage:) withObject:message];
}

- (void) parseMessage:(NSString *)message
{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    NSManagedObjectContext *BGMOC =  [[NSManagedObjectContext alloc] init];
    [BGMOC setPersistentStoreCoordinator:[self.appDelegate persistentStoreCoordinator]];

    //parse it
    //write to core data 

    NSNotificationCenter *dnc = [NSNotificationCenter defaultCenter];
    [dnc addObserver:self selector:@selector(addContextDidSave:)    name:NSManagedObjectContextDidSaveNotification object:BGMOC];

    NSError *saveError;
        if (![BGMOC save:&saveError]) {
            //handle the error
        }
    [dnc removeObserver:self name:NSManagedObjectContextDidSaveNotification object:BGMOC];
}

- (void)addContextDidSave:(NSNotification*)saveNotification {

// Merging changes causes the fetched results controller to update its results
[self.appDelegate.managedObjectContext   mergeChangesFromContextDidSaveNotification:saveNotification];
}

这似乎有效。

但Apple的文档说:在后台线程中保存容易出错。

所以我想知道这是否有效:

-(void) parseMessage:(NSString *)message 

{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 
   //parse it and save it to a dictionary
    [self performSelectorOnMainThread:@selector(saveToCoreData:) withObject:dictionary waitUntilDone:YES];
 [pool release];
}

在解析消息之后,我将其分组到一个字典中并将其传递给主线程并在那里执行核心数据。这有用吗?如果它有效,它会更好吗?

感谢。

1 个答案:

答案 0 :(得分:3)

Apple docs并未说明后台保存在技术上容易出错,他们暗示 程序员 在保存时容易出错背景:

  

异步队列和线程不会   防止应用程序退出。   (具体来说,所有基于NSThread的   线程是“分离的” - 看到了   完整的pthread文档   细节 - 一个过程只运行到   所有未分离的线程都已退出。)   如果您在执行保存操作   背景线程,因此,它可能   在它能够之前被杀死   完成。如果你需要保存   后台线程,你必须写   附加代码这样的主要   线程阻止应用程序   退出,直到所有保存操作   已经完成了。

翻译:“退出时,程序员必须特别注意后台操作的保存状态,而且很多时候他们没有。”

相关问题