Search code examples
cocoansstringnsurlnsfilemanager

What is the reason for NSFileManager's inconsistent use of NSURL?


I read somewhere that Apple encourages the use of NSURL over NSString in terms of paths and file locations, and this is becoming more obvious in new(er) API's - correct me if I am wrong. This Stack Overflow question deals with this topic in particular.

However, I noticed that some API's seem inconsistent regarding the use of NSURL and NSString - NSFileManager in particular. For example, NSFileManager has a method fileExistsAtPath: (which takes a NSString as the only argument), but there is no equivalent that takes a NSURL as the argument. To remove a file, though, there is a method that takes a NSString and an equivalent method that takes a NSURL.

Is there a reason for this discrepancy or has this historically grown?


Solution

  • Probably because they want to discourage the use of existence checks. As the header rather diplomatically puts it:

    The following methods are of limited utility. Attempting to predicate behavior based on the current state of the filesystem or a particular file on the filesystem is encouraging odd behavior in the face of filesystem race conditions. It's far better to attempt an operation (like loading a file or creating a directory) and handle the error gracefully than it is to try to figure out ahead of time whether the operation will succeed.