0

我有一个iOS应用程序正在从两个线程访问核心数据sql数据库。线程A(主UI线程)更新核心数据记录,然后线程B尝试从线程A刚刚更新的实体集合中读取数据。麻烦的是,线程B不能“看到”线程A持续存在的变化。iOS多线程核心数据应用程序未合并更改

线程B通过将NSOperation子类对象添加到NSOperationQueue来创建。在的NSOperation子类的主要方法如下:

@try { 
       // register for the moc save notification - this is so that other MOCs can be told to merge the changes 
       [[NSNotificationCenter defaultCenter] 
       addObserver:getApp() 
       selector:@selector(handleDidSaveNotification:) 
       name:NSManagedObjectContextDidSaveNotification 
       object:moc]; 

       NSError* error = nil; 
       if ([moc save:&error] == YES) 
       { 
        NSLog(@"%s SAVED FINE",__FUNCTION__); 

       }else { 
        NSLog(@"%s NOT saved, error=%@ %@",__FUNCTION__,error,[error localizedDescription]); 

       } 

       // unregister from notification 
       [[NSNotificationCenter defaultCenter] 
       removeObserver:getApp() 
       name:NSManagedObjectContextDidSaveNotification 
       object:moc]; 





      } 
      @catch (NSException * e) { 
       NSLog(@"%s Exception: %@",__FUNCTION__, e); 

      } 

主UI的appdelegate包含下面的代码来处理保存通知:

-(void) main { 

    // NEED to create the MOC here and pass to the methods. 
    NSManagedObjectContext* moc = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSConfinementConcurrencyType]; 

    [moc setUndoManager:nil]; 

    [moc setMergePolicy:NSMergeByPropertyStoreTrumpMergePolicy]; // Had been working for months 

    [moc setPersistentStoreCoordinator:getApp().persistentStoreCoordinator]; 

    [self doTheWorkWithMOC:moc]; // Actually performs updates, using moc 


    moc = nil; 



} 

后来,线程B如下保存它的变化

- (void)handleDidSaveNotification:(NSNotification*) note 
{ 

    @try { 

     // Notifications run on the same thread as the notification caller. 
     // However, we need to ensure that any db merges run on the main ui thread. 
     // Hence: 
     [self performSelectorOnMainThread:@selector(mergeContexts:) withObject:note waitUntilDone:NO]; 


    } 
    @catch (NSException * e) { 
     NSLog(@"appDelegate handleDidSaveNotification Exception: %@", e); 
    } 

} 
-(void)mergeContexts:(NSNotification*) note 
{ 
    if ([__managedObjectContext tryLock]==YES) 
    { 
     [__managedObjectContext mergeChangesFromContextDidSaveNotification:note]; 

     [__managedObjectContext unlock]; 
    } 

} 

大多数时候它都可以正常工作。

但是,我有一个iPad,在线程A读取数据库时,未检测到由线程B写入的更改。

任何人都可以看到我的代码中会导致这种情况的任何东西?

非常感谢

回答

0

熟练工,

首先,你应该移动到使用的iOS V5和狮推出了基于队列MOCS。这将使您更容易保持两个MOC同步。您将不再需要使用锁定系统。第二,一旦你移动到队列中的MOC,那么保持它们同步以响应“保存”通知是非常简单的。

第三,为什么你总是添加和删除保存通知的观察者?这对你看起来不可疑吗?显然,你错过了MOC之间的一些更新。

Andrew

+0

谢谢,我会按照这个建议。 – Journeyman