开发者

iphone - how to clear SQLite database?

I have an iphone app that is using a SQLite database, everything works and I can save the database to file and load开发者_运维技巧 it back up when the app is reloaded. But the problem i'm having is that I don't know how I can clear the database and start over from scratch.

I have tried deleting the database file, doing so will cause the app to start a new database from scratch the next time the app is restarted however I would like to know how to not just delete the database file but to also clear it out of memory all together and start a new database without needing to restart the app.


Your SQLite query should be something like this:

DELETE * from [table name]

... and you just repeat that for every table in the database.

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


So, you'd like to delete all *.sqlite files? There is no way to avoid looping, but you can limit it by using a predicate to filter out non-sql files first and ensure speedy performance using fast enumeration. Here's a method to do it:

-(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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜