2013-02-12 120 views
6

當我更新我的iOS應用程序時,我想刪除Documents目錄中任何現有的sqlite數據庫。現在,在應用程序更新上,我將數據庫中的數據庫複製到文檔目錄,並通過附加軟件包版本來命名它。因此,在更新中,我也想刪除任何可能存在的舊版本。iOS:如何從文檔目錄中刪除具有特定擴展名的所有現有文件?

我只希望能夠刪除所有sqlite文件,而不必循環查找以前的版本。有什麼辦法來通配removeFileAtPath:方法嗎?

+3

簡短的回答:沒有。你爲什麼不想循環?好有趣。 – trojanfoe 2013-02-12 16:35:20

+1

您需要使用NSFileManager來獲取匹配數組。 [示例代碼在這裏] [1]。 [1]:http://stackoverflow.com/a/4764532/1445366 – 2013-02-12 16:37:14

+0

什麼是規範的NSFileManager說? – 2013-02-12 16:47:00

回答

13

那麼,你想刪除所有*.sqlite文件?無法避免循環,但您可以通過使用NSPredicate來首先篩選非sql文件並使用快速枚舉確保快速性能來限制它。這裏有一個方法來做到這一點:

- (void)removeAllSQLiteFiles  
{ 
    NSFileManager *manager = [NSFileManager defaultManager]; 

    // the preferred way to get the apps documents directory 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 

    // grab all the files in the documents dir 
    NSArray *allFiles = [manager contentsOfDirectoryAtPath:documentsDirectory error:nil]; 

    // filter the array for only sqlite files 
    NSPredicate *fltr = [NSPredicate predicateWithFormat:@"self ENDSWITH '.sqlite'"]; 
    NSArray *sqliteFiles = [allFiles filteredArrayUsingPredicate:fltr]; 

    // use fast enumeration to iterate the array and delete the files 
    for (NSString *sqliteFile in sqliteFiles) 
    { 
     NSError *error = nil; 
     [manager removeItemAtPath:[documentsDirectory stringByAppendingPathComponent:sqliteFile] error:&error]; 
     NSAssert(!error, @"Assertion: SQLite file deletion shall never throw an error."); 
    } 
} 
+0

謝謝 - 代碼似乎工作,但是當我在管理器中檢查應用程序時,文件從未真正被刪除。這只是在開發模式下運行的一個「特徵」? – Michaela 2013-02-12 19:40:51

+0

@Michaela這是代碼中的一個錯誤。我沒有給出'removeItemAtPath'的完整路徑,以便找不到和刪除這些文件。現在修復。 – memmons 2013-02-13 15:59:54

+0

我會建議使用'NSError * error = nil;''error:&error'而不是'error:nil' for'removeItemAtPath:'然後你可以記錄錯誤,如果它存在可以幫助你調試任何問題。 – Robert 2013-02-13 16:01:44

相關問題