2009-11-22 35 views
9

Tôi có một ứng dụng tìm nạp dữ liệu từ internet và sử dụng CoreData để lưu trữ chúng trong thiết bị để có trải nghiệm mượt mà hơn.Xóa tất cả dữ liệu được lưu trữ với CoreData khi mô hình đã thay đổi

Vì tôi sử dụng Dữ liệu cốt lõi, mỗi khi lược đồ của tôi thay đổi, ứng dụng gặp sự cố khi tôi cố chạy ứng dụng đó với dữ liệu đã lưu trước đó trên thiết bị. Cách nhanh nhất để phát hiện thay đổi này và xóa tất cả dữ liệu khỏi thiết bị là gì, vì tôi không ngại tải xuống lại tất cả các dữ liệu đó. Nó đập đập và remapping lược đồ mới (trong trường hợp của tôi).

Tôi thấy rằng việc kiểm tra này được thực hiện trong getter:

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator 

vì vậy tôi chỉ cần biết phương pháp để thực hiện cho lau toàn bộ cơ sở dữ liệu và seting lên Core Data lần nữa. Cảm ơn :)

Trả lời

14

Quay lại câu hỏi này, để xóa tất cả dữ liệu khỏi bộ nhớ CoreData của tôi, tôi đã quyết định xóa tệp cơ sở dữ liệu sqlite đơn giản. Vì vậy, tôi chỉ thực hiện các NSPersistentStoreCoordinator như thế này:

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator { 

    if (persistentStoreCoordinator != nil) { 
     return persistentStoreCoordinator; 
    } 

    NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"myAppName.sqlite"]]; 

    NSError *error = nil; 
    persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; 
    if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error]) { 

     NSLog(@"Error opening the database. Deleting the file and trying again."); 

     //delete the sqlite file and try again 
     [[NSFileManager defaultManager] removeItemAtPath:storeUrl.path error:nil]; 
     if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error]) { 
      NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 
      abort(); 
     } 

     //if the app did not quit, show the alert to inform the users that the data have been deleted 
     UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"Error encountered while reading the database. Please allow all the data to download again." message:@"" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease]; 
     [alert show]; 
    } 

    return persistentStoreCoordinator; 
} 
+0

+1 Vì không có ai khác đã gợi ý một sự thay thế tốt hơn ... – RedBlueThing

+0

Tôi thực sự sử dụng này ngay bây giờ ... không thể tìm thấy một lựa chọn tốt. – Dimitris

Các vấn đề liên quan