【问题标题】:iOS: How to delete all existing files with specific extension from the documents dir?iOS:如何从文档目录中删除所有具有特定扩展名的现有文件?
【发布时间】:2013-01-28 00:50:20
【问题描述】:

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

我只是希望能够删除所有sqlite 文件,而不必循环查找以前版本的文件。有什么方法可以通配removeFileAtPath: 方法吗?

【问题讨论】:

  • 简短回答:不。你为什么不想循环播放?很有趣。
  • 您需要使用 NSFileManager 来获取匹配的数组。 [此处的示例代码][1]。 [1]:stackoverflow.com/a/4764532/1445366
  • NSFileManager 规范是怎么说的?

标签: ios cocoa-touch nsfilemanager


【解决方案1】:

那么,您想删除所有*.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.");
    }
}

【讨论】:

  • 谢谢 - 代码似乎可以工作,但当我在 Organizer 中检查应用程序时,该文件实际上从未被删除。这只是在开发模式下运行的“功能”吗?
  • @Michaela 这是代码中的一个错误。我没有给出removeItemAtPath 的完整路径,所以没有找到并删除这些文件。现已修复。
  • 我建议使用NSError* error = nil; error:&error 而不是error:nilremoveItemAtPath: 然后您可以记录错误(如果存在)以帮助您调试任何问题。
  • @罗伯特哈!当你发布时,我正在这样做。我更喜欢使用断言来确保我的大部分生产代码的有效性,而不是使用 NSLog。
【解决方案2】:

正确答案的 Swift 版本:

func removeAllSQLiteFiles() {
    let fileManager = FileManager.default

    let documentsDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
    let urlDocumentsDirectory = URL(fileURLWithPath: documentsDirectory)
    guard let allFiles = try? fileManager.contentsOfDirectory(at: urlDocumentsDirectory, includingPropertiesForKeys: nil) else {
        return
    }
    let sqliteFiles = allFiles.filter { $0.pathExtension.elementsEqual("sqlite") }
    for sqliteFile in sqliteFiles {
        do {
            try fileManager.removeItem(at: sqliteFile)
        } catch {
            assertionFailure(error.localizedDescription)
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-20
    • 2019-11-03
    • 2014-07-25
    • 2011-10-13
    • 1970-01-01
    • 1970-01-01
    • 2013-09-20
    相关资源
    最近更新 更多