如何使用NSFileManager删除目录及其内容

时间:2010-09-08 04:44:59

标签: iphone objective-c

Objective C的新手。我创建了一些包含iPhone应用程序pdf文件的目录。如何使用NSFileManager删除目录及其内容?

我是否需要首先循环并删除内容?任何代码示例都将非常感激。

提前致谢。

3 个答案:

答案 0 :(得分:48)

首先,通过Apple的NSFileManager iPhone文档查看是明智的:NSFileManager Class Reference。其次,查看NSFileManager的{​​{1}}方法及其文档。这就是你要找的东西。

答案 1 :(得分:35)

这是我使用的一些代码,我编辑了以适应问题

- (NSMutableString*)getUserDocumentDir {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSMutableString *path = [NSMutableString stringWithString:[paths objectAtIndex:0]];
    return path;
}


- (BOOL) createMyDocsDirectory
{
    NSMutableString *path = [self getUserDocumentDir];
    [path appendString:@"/MyDocs"];
    NSLog(@"createpath:%@",path);
    return [[NSFileManager defaultManager] createDirectoryAtPath:path
                                           withIntermediateDirectories:NO
                                           attributes:nil 
                                           error:NULL];
}

- (BOOL) deleteMyDocsDirectory 
{
    NSMutableString *path = [self getUserDocumentDir];
    [path appendString:@"/MyDocs"];
    return [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
}

答案 2 :(得分:0)

您可以使用此获取文档目录:

NSString *directoryPath = [NSHomeDirectory() stringByAppendingString:@"/Documents/"];

** 使用以下命令删除完整目录路径:

BOOL success = [fileManager removeItemAtPath:directoryPath error:nil];
if (!success) {
    NSLog(@"Directory delete failed");
}

** 使用以下命令删除该目录的内容:

NSFileManager *fileManager = [NSFileManager defaultManager];    
if ([fileManager fileExistsAtPath:directoryPath]) {
            NSDirectoryEnumerator *dirEnum = [fileManager enumeratorAtPath:directoryPath];
            NSString *documentsName;
            while (documentsName = [dirEnum nextObject]) {
                NSString *filePath = [directoryPath stringByAppendingString:documentsName];
                BOOL isFileDeleted = [fileManager removeItemAtPath:filePath error:nil];
                if(isFileDeleted == NO) {
                    NSLog(@"All Contents not removed");
                    break;
                }
            }
            NSLog(@"All Contents Removed");
        }

** 您可以根据需要编辑 directoryPath