2011-02-05 6 views
2

私のアプリは、初めて使用するときに、WebベースのXMLフィードから必要なデータをダウンロードするように設定されています。Core Dataデータベースをリフレッシュする正しい方法

ユーザは、設定によって定期的にデータを更新するオプションもあります。

これを行うとき、私は既存のデータベースを削除し、最初の読み込みに使用するコードで再作成します。

私は、単にデータベースを削除することは正しい方法ではありませんので、新しいデータセットを読み込む前に以下の方法でデータを破棄しています。データの更新を実行するとき

- (void)resetApplicationModel { 

NSURL *_storeURL = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: DBSTORE]]; 
NSPersistentStore *_store = [persistentStoreCoordinator persistentStoreForURL:_storeURL]; 
[persistentStoreCoordinator removePersistentStore:_store error:nil]; 
[[NSFileManager defaultManager] removeItemAtPath:_storeURL.path error:nil]; 

[persistentStoreCoordinator release], persistentStoreCoordinator = nil; 
} 

しかし、これは動作しませんが、それは、データをダウンロードしますが、それをデータベースに保存することはできませんし、コンソールに次のエラーを生成します。

このNSPersistentStoreCoordinatorには、永続ストアはありません。保存操作は実行できません。

データベースを更新するための「正しい」方法は何ですか?

答えて

1

「正しい」方法は、すべてのオブジェクトをフェッチし、それぞれを削除してからコンテキストを保存することです。 (http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CoreData/Articles/cdFetching.html)

- (void) deleteAllEntitiesForName:(NSString*)entityName { 
    NSManagedObjectContext *moc = [self managedObjectContext]; 
    NSEntityDescription *entityDescription = [NSEntityDescription 
     entityForName:entityName inManagedObjectContext:moc]; 
    NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease]; 
    [request setEntity:entityDescription]; 
    NSError *error = nil; 
    NSArray *array = [moc executeFetchRequest:request error:&error]; 
    if (array != nil) { 
     for(NSManagedObject *managedObject in array) { 
      [moc deleteObject:managedObject]; 
     } 
     error = nil; 
     [moc save:&error]; 
    } 

} 

その後、あなたは自分のオブジェクトを再作成することができます。

+0

"if(array == nil)"は "if(array!= nil)"にする必要があります。 –

+0

はい、正しくありがとうございます。私はそれを修正するために自分のコードを編集しました。 –

関連する問題