Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS: How to delete all existing files with specific extension from the documents dir?

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?

like image 685
Michaela Avatar asked Feb 12 '13 16:02

Michaela


People also ask

How do I remove all files from a specific extension?

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.


1 Answers

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.");
    }
}
like image 93
memmons Avatar answered Sep 21 '22 02:09

memmons