iOS:如何从文档目录中删除具有特定扩展名的所有现有文件?

Mic*_*ela 6 cocoa-touch nsfilemanager ios

当我更新我的iOS应用程序时,我想删除目录sqlite中的任何现有数据库Documents.现在,在应用程序更新时,我将数据库从软件包复制到文档目录,并通过附加软件包版本来命名它.因此,在更新时,我还想删除可能存在的任何旧版本.

我只是希望能够删除所有sqlite文件,而无需循环浏览并查找以前版本的文件.有没有办法通配符这个removeFileAtPath:方法?

mem*_*ons 15

那么,你想删除所有*.sqlite文件?没有办法避免循环,但您可以通过使用a NSPredicate来过滤掉非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.");
    }
}
Run Code Online (Sandbox Code Playgroud)