2010-10-19 110 views
2

我有一個iPhone應用程序正在使用SQLite數據庫,一切正常,我可以將數據庫保存到文件並在應用程序重新加載時將其加載備份。但我遇到的問題是我不知道如何清除數據庫並從頭開始。iphone - 如何清除SQLite數據庫?

我已經嘗試刪除數據庫文件,這樣做會導致應用程序從頭開始新的數據庫下次重新啓動應用程序但是我想知道如何不只是刪除數據庫文件,但也清除它會在內存不足的情況下一起啓動新的數據庫,而無需重新啓動應用程序。

回答

0

所以,你想刪除所有* .sqlite文件?沒有辦法避免循環,但是可以通過使用謂詞來首先篩選非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."); 
    } 
}