微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/iOS/330756.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐