7

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

我只想能够删除所有sqlite文件,而不必遍历并查找以前版本的文件。有没有办法给removeFileAtPath:方法通配符?

4

2 回答 2

17

那么,您想删除所有*.sqlite文件吗?没有办法避免循环,但您可以通过使用 aNSPredicate来限制它,先过滤掉非 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.");
    }
}
于 2013-02-12T16:55:51.733 回答
0

正确答案的 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)
        }
    }
}
于 2021-09-01T23:14:05.843 回答