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

一个人想着一个人 提交于 2019-12-09 18:01:16

问题


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?


回答1:


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.");
    }
}


来源:https://stackoverflow.com/questions/14837218/ios-how-to-delete-all-existing-files-with-specific-extension-from-the-documents

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!