gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 03:37:52 25 4
gpt4 key购买 nike

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

我只想删除所有 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.");
}
}

关于iOS:如何从文档目录中删除所有具有特定扩展名的现有文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14837218/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com