NSFileManager删除目录的内容

Ver*_*ous 33 directory cocoa nsfilemanager osx-snow-leopard

如何在不删除目录本身的情况下删除目录的所有内容?我想基本上清空一个文件夹,但保留它(和权限)完整.

Geo*_*che 83

例如,通过使用目录枚举器:

NSFileManager *fileManager = [[NSFileManager alloc] init];
NSDirectoryEnumerator *enumerator = [fileManager enumeratorAtPath:path];    
NSString *file;

while (file = [enumerator nextObject]) {
    NSError *error = nil;
    BOOL result = [fileManager removeItemAtPath:[path stringByAppendingPathComponent:file] error:&error];

    if (!result && error) {
        NSLog(@"Error: %@", error);
    }
}
Run Code Online (Sandbox Code Playgroud)

迅速

let fileManager = NSFileManager.defaultManager()
let enumerator = fileManager.enumeratorAtURL(cacheURL, includingPropertiesForKeys: nil, options: nil, errorHandler: nil)

while let file = enumerator?.nextObject() as? String {
    fileManager.removeItemAtURL(cacheURL.URLByAppendingPathComponent(file), error: nil)
}
Run Code Online (Sandbox Code Playgroud)

  • @Psycho:对于Objective-C来说是真的,但是对于Objective-C++来说效果很好.当这与问题无关且容易修复时值得投票吗?我不这么认为...... (3认同)
  • 在尝试使用错误对象之前,不要忘记检查`removeItemAtPath:`是否真的失败了.至少,您可能会报告比实际更多的错误. (2认同)

Jac*_*kin 11

试试这个:

NSFileManager *manager = [NSFileManager defaultManager];
NSString *dirToEmpty = ... //directory to empty
NSError *error = nil;
NSArray *files = [manager contentsOfDirectoryAtPath:dirToEmpty 
                                              error:&error];

if(error) {
  //deal with error and bail.
}

for(NSString *file in files) {
    [manager removeItemAtPath:[dirToEmpty stringByAppendingPathComponent:file]
                        error:&error];
    if(error) {
       //an error occurred...
    }
}    
Run Code Online (Sandbox Code Playgroud)


Max*_*Max 5

在swift 2.0中:

if let enumerator = NSFileManager.defaultManager().enumeratorAtPath(dataPath) {
  while let fileName = enumerator.nextObject() as? String {
    do {
        try NSFileManager.defaultManager().removeItemAtPath("\(dataPath)\(fileName)")
    }
    catch let e as NSError {
      print(e)
    }
    catch {
      print("error")
    }
  }
}
Run Code Online (Sandbox Code Playgroud)