iOS:如何从文档目录中删除具有特定扩展名的所有现有文件? [英] iOS: How to delete all existing files with specific extension from the documents dir?

查看:186
本文介绍了iOS:如何从文档目录中删除具有特定扩展名的所有现有文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新iOS应用程式时,我要删除 Documents 目录中任何现有的 sqlite 资料库。现在,在应用程序更新上,我将数据库从捆绑包复制到文档目录,并通过附加捆绑软件版本来命名。所以,在更新,我也想删除任何可能存在的旧版本。

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.

我只是希望能够删除所有 sqlite 文件,而不必循环遍历,之前的版本。有没有办法通配符 removeFileAtPath:方法?

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?

推荐答案

因此,您要删除所有 *。sqlite 文件?没有办法避免循环,但您可以通过使用 NSPredicate 首先过滤掉非sql文件并使用快速枚举确保快速性能来限制它。这里有一个方法:

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

这篇关于iOS:如何从文档目录中删除具有特定扩展名的所有现有文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆