iphone - 如何清除SQLite数据库?

时间:2010-10-19 22:01:54

标签: iphone sqlite

我有一个使用SQLite数据库的iphone应用程序,一切正常,我可以将数据库保存到文件并在重新加载应用程序时加载它。但我遇到的问题是我不知道如何清理数据库并从头开始。

我尝试删除数据库文件,这样做会导致应用程序在下次重新启动应用程序时从头开始创建新数据库但是我想知道如何不仅删除数据库文件而且还要清除它内存不足并启动新数据库而无需重新启动应用程序。

2 个答案:

答案 0 :(得分:1)

您的SQLite查询应该是这样的:

DELETE * from [table name]

...你只需对数据库中的每个表重复一次。

价: http://www.sqlite.org/lang_delete.html

答案 1 :(得分: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.");
    }
}
相关问题