NSManagedContext返回旧数据而不是新

时间:2017-07-28 06:51:05

标签: ios database core-data nsmanagedobjectcontext nspersistentstore

在我的应用程序中,我使用了NSManagedContext的Double Model。 让一个孩子managedObjectContextNSMainQueueConcurrencyType和父母一起 writerManagedObjectContext NSPrivateQueueConcurrencyType PersistentStoreCoordinator将数据保存到parent context。我能够在数据库中保存数据,但在检索时我得到旧值而不是新值。

下面的代码是将上下文保存到PersistentStoreCoordinator,然后保存到 [managedObjectContext performBlock:^{ //push to parent //NSLog(@"pushing to parent context (writer context)"); NSError * error; if([managedObjectContext hasChanges] && ![managedObjectContext save:&error]){ NSLog(@"main Save Error: %@", [error localizedDescription]); } //NSLog(@"pushing to persistentstore"); [self.writerManagedObjectContext performBlock:^{ //push to parent NSError * error; if([self.writerManagedObjectContext hasChanges] && ![self.writerManagedObjectContext save:&error]){ NSLog(@"writer Save Error: %@", [error localizedDescription]); } }]; }];

@dt TVP_API_DELIVERY_ORDER  READONLY    
    UPDATE  Stkm SET
            Stkm.Itm_Qty_OnHand = CASE 
                                    WHEN tvp.Flag='I' THEN (Itm_Qty_OnHand- (SELECT SUM(T1.OrderQty) FROM @dt T1 WHERE T1.ItemCode=tvp.ItemCode)) 
                                    WHEN tvp.Flag='U' THEN ((Itm_Qty_OnHand+(SELECT SUM(T2.Dod_Qty) FROM DoD T2 WHERE T2.Itm_cd=tvp.ItemCode AND T2.Do_No=@OrderNo AND T2.Do_Year=@Year))-(SELECT SUM(T3.OrderQty) FROM @dt T3 WHERE T3.ItemCode=tvp.ItemCode))
                                    WHEN tvp.Flag='D' THEN (Itm_Qty_OnHand + (SELECT SUM(T4.Dod_Qty) FROM DoD T4 WHERE T4.Itm_cd=tvp.ItemCode AND T4.Do_No=@OrderNo AND T4.Do_Year=@Year))                                          
                                    ELSE 0
                                  END       
    FROM     @dt tvp 
    INNER JOIN Stkm ON tvp.ItemCode=Stkm.Itm_Cd

在堆栈溢出时找到相同的issue,但它的答案对我的问题没有帮助。谁知道怎么做?

1 个答案:

答案 0 :(得分:0)

将主要上下文的automaticallyMergesChangesFromParent设置为YES。

写入上下文直接与PersistentStoreCoordinator对话,因此主要上下文无法知道有任何更改。上下文具有缓存,并且不总是访问数据库以获取数据。在iOS 10之前,您需要监控通知并致电mergeChangesFromContextDidSaveNotification;在iOS 10中添加了automaticallyMergesChangesFromParent,这使得这更容易。