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

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

我只是希望能够删除所有sqlite文件,而无需循环浏览并查找以前版本的文件.是否有任何方法可以对removeFileAtPath:方法进行通配符?

解决方法

那么,你想要删除所有* .sqlite文件?无法避免循环,但您可以通过使用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.");
    }
}

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...