When I update my iOS app, I want to delete any existing sqlite
databases in the Documents
directory. Right now, on an application update, I copy the database from the bundle to the documents directory and name it by appending the bundle version. So, on the update, I also want to delete any old versions that might exist.
I just want to be able to delete all sqlite
files, without having to loop through and look for ones from previous versions. Is there any way to wildcard the removeFileAtPath:
method?
To remove files with a specific extension, we use the 'rm' (Remove) command, which is a basic command-line utility for removing system files, directories, symbolic links, device nodes, pipes, and sockets in Linux. Here, 'filename1', 'filename2', etc. are the names of the files including full path.
So, you'd like to delete all *.sqlite
files? There is no way to avoid looping, but you can limit it by using a NSPredicate
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.");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With