日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

07-CoreData清除所有数据

發(fā)布時間:2024/9/30 编程问答 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 07-CoreData清除所有数据 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.


CoreData清空數(shù)據(jù)庫

  • 清空數(shù)據(jù)庫可以使用刪除文件的方式

  • 通過沙盒路徑進入到沙盒可以看到數(shù)據(jù)庫文件有三個,我們逐一刪除便可

  • 代碼中的kFileName是一個宏 表示創(chuàng)建的數(shù)據(jù)庫文件名




    NSFileManager *fileManager = [NSFileManager defaultManager];NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];//沙盒中三個文件NSString *filePath1 = [documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.db",kFileName]];NSString *filePath2 = [documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.db-shm",kFileName]];NSString *filePath3 = [documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.db-wal",kFileName]];NSError *error;BOOL success = [fileManager removeItemAtPath:filePath1 error:&error];[fileManager removeItemAtPath:filePath2 error:nil];[fileManager removeItemAtPath:filePath3 error:nil];if (success) {NSLog(@"Remove fiel:%@ Success!",kFileName);}else{NSLog(@"Could not delete file -:%@ ",[error localizedDescription]);}


    CoreData清空數(shù)據(jù)庫實際開發(fā)中注意事項


    1.從原則上來講,清空數(shù)據(jù)庫時直接刪除數(shù)據(jù)庫文件的效率和便利性遠大于先從數(shù)據(jù)庫中取數(shù)據(jù)然后逐一刪除 2.但是雖然刪除了數(shù)據(jù)庫文件,繼續(xù)從CoreData Stack技術棧堆中查詢數(shù)據(jù)仍然可以查詢到,這是因為在上一次的查詢過程中,數(shù)據(jù)庫中的數(shù)據(jù)已經(jīng)被緩存到內(nèi)存。 3.網(wǎng)上有很多示例,要想清除CoreData緩存,ARC下直接設置CoreDataStack元素為nil

    kManagedObjectContext.managedObjectContext =nil;

    ? ? kManagedObjectContext.persistentStoreCoordinator =nil;

    ? ? kManagedObjectContext.persistentStore =nil;


    我認為這樣寫是不專業(yè)的,如果需要再次使用就必須要重新初始化CoreData Stack,非常損耗性能


    4.由于之前講解過CoreData Stack中真正進行儲存數(shù)據(jù)操作的是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];


總結

以上是生活随笔為你收集整理的07-CoreData清除所有数据的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。