iOS - iPhone应用程序文档"没有这样的目录"?

gol*_*enk 1 nsurl nsstring nsfilemanager ios

我正在尝试使用解决方案的方法来删除我正在编写的应用程序的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);
}
Run Code Online (Sandbox Code Playgroud)

但是当我尝试运行它时,由于传递的内容被解释为不存在的目录,因此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

)}
Run Code Online (Sandbox Code Playgroud)

据我所知,打印到NSLog的路径看起来正确,所以我不确定我做错了什么.任何人都可以向我指出我的错误在哪里吗?非常感谢!

rma*_*ddy 8

你获得价值的代码directory并不完全正确.你要:

NSURL *directoryURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
NSString *directory = [directoryURL path];
Run Code Online (Sandbox Code Playgroud)

调用absoluteStringNSURL给你一个文件的URL.您不希望文件URL,您希望将文件URL转换为文件路径.这就是path方法的作用.

另一种方式是:

NSString *directory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
Run Code Online (Sandbox Code Playgroud)