2016-06-13 3 views
0

コアデータを使用している間に奇妙なデータ損失に直面しています。アプリケーションが2回目に実行された場合、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"]; 
     }]; 
    } 

次のコードを使用してレコードを取得します。

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にはいくつかのコンテンツがあります。アプリケーションを手動で終了せずにアプリケーションを2回目に実行しているかのように、self.domainContextはその中に内容を持っていません。しかし、私が手動でアプリケーションを終了すると、アプリケーションを再実行すると、self.domainContextはコンテンツを保存しています。どうしてこんなことに?私は手動で私のアプリを閉じる場合にのみ、データはディスクに永続化されています。アプリを手動で閉じずにxcodeからアプリを実行すると、データが永続化されません。

答えて

1

コンテキストを保存していないので、2回目にデータが失われました。このようなコードを変更してください

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

私は、ループの後で繰り返しを行うときよりも保存操作を使う方が良いと思います。 –

関連する問題