2011-06-10 95 views
3

我有這個後臺線程,做核心數據對象的一些事情。我得到的背景如下:核心數據和多線程(和綁定,使其更有趣)

- (id)_managedObjectContextForThread; 
{  
    NSManagedObjectContext * newContext = [[[NSThread currentThread] threadDictionary] valueForKey:@"managedObjectContext"]; 
    if(newContext) return newContext; 

    newContext = [[NSManagedObjectContext alloc] init]; 
    [newContext setPersistentStoreCoordinator:[[[NSApplication sharedApplication] delegate] persistentStoreCoordinator]]; 
    [[NSNotificationCenter defaultCenter] addObserver:self 
             selector:@selector(_mergeChangesFromManagedObjectContext:) 
              name:NSManagedObjectContextDidSaveNotification 
              object:newContext]; 

    [[[NSThread currentThread] threadDictionary] setValue:newContext forKey:@"managedObjectContext"]; 
    return newContext; 
} 

然後我取一些對象,對其進行修改並保存上下文:

- (void) saveContext:(NSManagedObjectContext*)context { 
    NSError *error = nil; 
    if (![context save:&error]) { 
     [[NSApplication sharedApplication] presentError:error]; 
    } 
} 

- (void)_mergeChangesFromManagedObjectContext:(NSNotification*)notification; 
{ 
    [[[[NSApplication sharedApplication] delegate] managedObjectContext] performSelectorOnMainThread:@selector(mergeChangesFromContextDidSaveNotification:) 
                        withObject:notification 
                       waitUntilDone:YES]; 
} 

..後來我刪除觀察者。這適用於主要部分。但是一些屬性在合併後不會更新。更新前沒有的屬性。那些有價值的人保持不變。

我想:

[newContext setMergePolicy:NSOverwriteMergePolicy]; 

...(和其他的合併政策)的主要方面,但沒有奏效:P

謝謝您的幫助。

注:我已經將值綁定到NSTableView。我合併後記錄他們。值爲零的屬性似乎工作正常。

回答

5

你如何爲通知註冊兩個上下文?你需要做這樣的事情:

NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; 

[nc addObserver:self 
     selector:@selector(backgroundContextDidSave:) 
      name:NSManagedObjectContextDidSaveNotification 
     object:backgroundMOC]; 

[nc addObserver:self 
     selector:@selector(mainContextDidSave:) 
      name:NSManagedObjectContextDidSaveNotification 
     object:mainMOC]; 

並實現回調:

// merge changes in background thread if main context changes 
- (void)mainContextDidSave:(NSNotification *)notification 
{ 
    SEL selector = @selector(mergeChangesFromContextDidSaveNotification:); 
    [backgroundMOC performSelector:selector onThread:background_thread withObject:notification waitUntilDone:NO]; 
} 


// merge changes in main thread if background context changes 
- (void)backgroundContextDidSave:(NSNotification *)notification 
{ 
    if ([NSThread isMainThread]) { 
     [mainMOC mergeChangesFromContextDidSaveNotification:notification]; 
    } 
    else { 
     [self performSelectorOnMainThread:@selector(backgroundContextDidSave:) withObject:notification waitUntilDone:NO]; 
    } 
} 
+1

我把它遍佈到的NSOperation,並聽取了主背景也嘗試過。沒有工作:P然後,我發現了一個行,在更新主線程中的值之前,將管理對象ID提供給修改線程。在此之前我沒有保存上下文。現在我在mofifing線程之前保存上下文,一切正常。感謝您的幫助 – david 2011-06-11 09:42:41