2016-06-13 27 views
0

在使用核心數據時,我正面臨奇怪的數據丟失。如果應用程序第二次運行,從executeFetchRequest返回的記錄爲空

使用以下代碼將記錄保存到核心數據。

for (int i = 0; i < [domains count]; i++){ 

     NSString *is_active = [[domains objectAtIndex:i] objectForKey:@"is_active"]; 
     NSString *domain_id = [[domains objectAtIndex:i] objectForKey:@"domain_id"]; 
     NSString *domain_name = [[domains objectAtIndex:i] objectForKey:@"domain_name"]; 

     [context performBlockAndWait:^{ 
      NSManagedObject *domain = [NSEntityDescription insertNewObjectForEntityForName:@"Domains" inManagedObjectContext:context]; 
      [domain setValue:is_active forKey:@"isActive"]; 
      [domain setValue:domain_id forKey:@"domainId"]; 
      [domain setValue:domain_name forKey:@"domainName"]; 
     }]; 
    } 

Im使用下面的代碼來獲取記錄。

NSError *error; 
    NSManagedObjectContext *managedObjectContext = [self managedObjectContext]; 

    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Domains"]; 

    self.domainContext = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy]; 

    NSLog(@"domain context %@",self.domainContext); 

我正在使用真實設備進行測試。

如果我第一次在設備上運行應用程序,self.domainContext已經獲得了一些內容。在那裏,如果第二次運行應用程序而不手動關閉應用程序,self.domainContext沒有任何內容。但是,如果我手動關閉應用程序並重新運行應用程序,則self.domainContext已保存了內容。爲什麼?只有當我手動關閉我的應用程序時,數據纔會持久保存到磁盤。如果我在沒有手動關閉我的應用程序的情況下從xcode運行應用程序,則數據不會被持久保存。

回答

1

您沒有保存上下文。所以您第二次丟失了數據。改變你的代碼這樣

for (int i = 0; i < [domains count]; i++){ 

    NSString *is_active = [[domains objectAtIndex:i] objectForKey:@"is_active"]; 
    NSString *domain_id = [[domains objectAtIndex:i] objectForKey:@"domain_id"]; 
    NSString *domain_name = [[domains objectAtIndex:i] objectForKey:@"domain_name"]; 

    [context performBlockAndWait:^{ 
     NSManagedObject *domain = [NSEntityDescription insertNewObjectForEntityForName:@"Domains" inManagedObjectContext:context]; 
     [domain setValue:is_active forKey:@"isActive"]; 
     [domain setValue:domain_id forKey:@"domainId"]; 
     [domain setValue:domain_name forKey:@"domainName"]; 
    }]; 
    NSError *error = nil; 
    [context save:&error]; 
} 

希望這會幫助你。

+0

8小時的調試終於結束了,因爲您的寶貴解決方案。關閉兄弟 – Roger

+0

提到不兄弟 – Roger

+1

我認爲在循環後使用保存操作比在每次迭代中更好 –

相關問題