2013-10-28 48 views
0

我正在完成檢查清單上的一些項目。我使用下面的方法計算已完成的項目:使用核心數據最新保存的數據

- (NSUInteger)completedCount { 
return [DIDTask MR_countOfEntitiesWithPredicate:[NSPredicate predicateWithFormat:@"completed == YES && list == %@", self]]; 
} 

當我打電話名單上的方法,我的問題是 - list.completedCount - 數據保存後立即它不給我正確的數量,而是值 - 1.只有當應用程序更改屏幕或顯示彈出窗口(如下所示)後,list.completedCount纔會給我正確的值。但這對我來說太遲了。

[UIAlertView showAlertViewWithTitle:@"Are you OK?" message:task.name cancelButtonTitle:@"Stop" otherButtonTitles:@[@"Yes", @"No"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) { 
     if (buttonIndex > 0) { 
      [MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext) { 
       [[task MR_inContext:localContext] setCompletedValue:buttonIndex == 1]; 
      } completion:^(BOOL success, NSError *error) { 
      }]; 
      [self continueAutomaticModeWithList:list taskIndex:index + 1]; 
     } 
    }]; 

我的問題是我怎麼可以更新或立即刷新應用程序時,數據被保存,以便list.completedCount給了我正確的計數,對嗎?

回答

2

它不起作用,因爲[self continueAutomaticModeWithList:list taskIndex:index + 1];在保存完成之前執行。您必須將其移至完成塊:

[UIAlertView showAlertViewWithTitle:@"Are you OK?" message:task.name cancelButtonTitle:@"Stop" otherButtonTitles:@[@"Yes", @"No"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) { 
    if (buttonIndex > 0) { 
     [MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext) { 
      [[task MR_inContext:localContext] setCompletedValue:buttonIndex == 1]; 
     } completion:^(BOOL success, NSError *error) { 
      [self continueAutomaticModeWithList:list taskIndex:index + 1]; 
     }]; 
    } 
}]; 
+0

已解決。謝謝!甚至沒有必要把「weakSelf」放在一邊...我直接和「Self」一起去了,它工作。那麼爲什麼我應該使用「weakSelf」來代替它? – Armand

+0

@Armand:你說得對。沒有一個塊被'self'保留,所以'__weak'修飾符在這裏不需要。 –