【问题标题】:iOS - iPhone application documents "No such directory"?iOS - iPhone应用程序文档“没有这样的目录”?
【发布时间】:2013-04-15 15:00:57
【问题描述】:

我正在尝试使用the solution here 中看到的方法来删除我正在编写的应用程序的 iPhone 文档目录中的所有文件。为了传入文档目录的字符串位置,我对解决方案中的代码进行了一些小的更改。我的代码版本如下:

NSString *directory = [[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject] absoluteString];
NSLog(@"%@", directory);
NSError *error = nil;
NSArray *directoryContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:directory error:&error];
if (error == nil) {
    for (NSString *path in directoryContents) {
        NSString *fullPath = [directory stringByAppendingPathComponent:path];
        BOOL removeSuccess = [[NSFileManager defaultManager] removeItemAtPath:fullPath error:&error];
        if (!removeSuccess) {
            // Error handling
        }
    }
} else {
    // Error handling
    NSLog(@"%@", error);
}

但是,当我尝试运行它时,由于传递的内容被解释为不存在的目录,因此 directoryContents 的设置失败。具体来说,我在代码中放入的两个 NSLog() 语句返回以下内容:

2013-04-22 11:48:22.628 iphone-ipcamera[389:907] file://localhost/var/mobile/Applications/AB039CDA-412B-435A-90C2-8FBAADFE6B1E/Documents/

2013-04-22 11:48:22.650 iphone-ipcamera[389:907] Error Domain=NSCocoaErrorDomain Code=260 "The operation couldn’t be completed. (Cocoa error 260.)" UserInfo=0x1d5232c0 {NSUnderlyingError=0x1d54c420 "The operation couldn’t be completed. No such file or directory", NSFilePath=file://localhost/var/mobile/Applications/AB039CDA-412B-435A-90C2-8FBAADFE6B1E/Documents/, NSUserStringVariant=(

    Folder

)}

据我所知,打印到 NSLog 的路径看起来是正确的,所以我不确定我做错了什么。谁能指出我的错误在哪里?非常感谢!

【问题讨论】:

    标签: ios nsstring nsurl nsfilemanager


    【解决方案1】:

    您获取directory 值的代码不太正确。你想要:

    NSURL *directoryURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
    NSString *directory = [directoryURL path];
    

    NSURL 上调用absoluteString 会给你一个文件URL。您不需要文件 URL,而是希望将文件 URL 转换为文件路径。这就是path 方法的作用。

    另一种方式是:

    NSString *directory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    

    【讨论】:

    • 胜利。谢谢你,先生。按描述工作,我很欣赏关于为什么我以前的方法不起作用的解释。
    • 更好的是,致电-[NSFileManager contentsOfDirectoryAtURL:…] 并完全避免使用路径
    • 使用path 而不是absoluteString 解决了我的问题!
    猜你喜欢
    • 2012-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-16
    • 1970-01-01
    • 2019-12-29
    • 2012-01-11
    • 2020-08-18
    相关资源
    最近更新 更多