07-CoreData清除所有資料
CoreData清空資料庫
-
清空資料庫可以使用刪除檔案的方式
-
通過沙盒路徑進入到沙盒可以看到資料庫檔案有三個,我們逐一刪除便可
-
程式碼中的kFileName是一個巨集 表示建立的資料庫檔名
NSFileManager *fileManager = [NSFileManager defaultManager]; NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; //沙盒中三個檔案
CoreData清空資料庫實際開發中注意事項
1.從原則上來講,清空資料庫時直接刪除資料庫檔案的效率和便利性遠大於先從資料庫中取資料然後逐一刪除 2.但是雖然刪除了資料庫檔案,繼續從CoreData Stack技術棧堆中查詢資料仍然可以查詢到,這是因為在上一次的查詢過程中,資料庫中的資料已經被快取到記憶體。 3.網上有很多示例,要想清除CoreData快取,ARC下直接設定CoreDataStack元素為nilkManagedObjectContext.managedObjectContext =nil;
kManagedObjectContext.persistentStoreCoordinator =nil;
kManagedObjectContext.persistentStore =nil;
我認為這樣寫是不專業的,如果需要再次使用就必須要重新初始化CoreData Stack,非常損耗效能
4.由於之前講解過CoreData Stack中真正進行儲存資料操作的是NSPersistentStore(儲存器),所以這裡只需要移除儲存器再重新新增便可
NSURL *url = [[kManagedObjectContextgetDocumentsUrl]URLByAppendingPathComponent:@"mysql.db"isDirectory:YES];
NSLog(@"%@",kManagedObjectContext.persistentStoreCoordinator.persistentStores);
[kManagedObjectContext.persistentStoreCoordinatorremovePersistentStore:kManagedObjectContext.persistentStoreCoordinator.persistentStores[0]error:nil];
[kManagedObjectContext.persistentStoreCoordinatoraddPersistentStoreWithType:NSSQLiteStoreTypeconfiguration:nilURL:urloptions:nilerror:nil];
[self.tableViewreloadData];