NSFileManager delete contents of directory

后端 未结 9 1839
你的背包
你的背包 2021-01-30 17:13

How do you delete all the contents of a directory without deleting the directory itself? I want to basically empty a folder yet leave it (and the permissions) intact.

9条回答
  •  滥情空心
    2021-01-30 17:36

    Try this:

    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...
        }
    }    
    

提交回复
热议问题