Search code examples
iosmacoscocoansfilemanager

NSFileManager, how to determine if a file or directory can be removed?


Is there a way to tell, if calling

[[NSFileManager defaultManager] removeItemAtPath:filePath error:NULL];

will fail?


Solution

  • I think you want to check out NSFileManager's -isDeletableFileAtPath: which works for both files and directories https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/Reference/Reference.html#//apple_ref/occ/instm/NSFileManager/isDeletableFileAtPath:

    However, you should probably heed the note listed in the documentation:

    Note: Attempting to predicate behavior based on the current state of the file system or a particular file on the file system is not recommended. Doing so can cause odd behavior or race conditions. It's far better to attempt an operation (such as loading a file or creating a directory), check for errors, and handle those errors gracefully than it is to try to figure out ahead of time whether the operation will succeed. For more information on file system race conditions, see “Race Conditions and Secure File Operations” in Secure Coding Guide.

    Try to remove it and check for errors instead of passing NULL