2014-04-12 27 views
0

我想知道如果你可以經常調用NSManagedObjectContext保存。我保存的代碼是標準的UIApplicationDelegate代碼:調用NSManagedObjectContext上的saveContext太多

- (void)saveContext 
{ 
    NSError *error = nil; 
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext; 
    if (managedObjectContext != nil) { 
     if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) { 
      // Replace this implementation with code to handle the error appropriately. 
      // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
      NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 
      abort(); 
     } 
    } 
} 

我帶來了一個模式,以創建一個新的報警類型對象的應用程序。模態有幾個屏幕,像重複的日子。類似於Apple重複的日子觀點,我推出了一個新的viewController,它顯示了重複的日子。當我回到用戶輸入鬧鐘名稱的模式主屏幕時,是否可以調用saveContext?我想我想知道是否需要擔心爲較小的屏幕調用saveContext,如重複的日子,然後用戶在主模態屏幕上點擊完成,然後立即再次調用saveContext。

回答

0

如果您在整個應用程序中只有一個NSManagedObjectContext,則不必在上下文中經常調用-save(只要您的應用程序不會崩潰!)。在這種情況下,我通常會在離開編輯屏幕時保存,如果一些信息已被更改,並保存在應用程序代理-applicationDidEnterBackground:中。

如果您有很多更改(新對象,更新等),那麼調用save會有點貴,因爲它必須將這些更改寫入持久存儲區(磁盤上的文件 - 假設您'通常使用NSPersistedStore)。