Search code examples
iosobjective-cmultithreadingthread-safetynsfilemanager

What does it mean for iOS FileManager to be thread-safe?


I'm reading/writing files and folders in a multithreaded iOS app. I want these operations to be thread-safe.

NSFileManager's documentation says that "you should create a unique instance of the file manager object, assign your delegate to that object, and use that file manager to initiate your operations."

Such types of functions are used ( the classification is mine ):

"Writing" operations:

  • NSData writeToFile: options:NSDataWritingAtomic
  • NSFileManager createDirectoryAtPath
  • NSFileManager createFileAtPath
  • NSFileManager removeItemAtPath

"Reading" operations:

  • NSFileManager fileExistsAtPath
  • NSFileManager subpathsAtPath

I'm choosing between such options for ensuring thread safety:

  1. Create two NSFileManagers: one for "Writing" operations, one for "Reading" operations. I call only atomic write, so NSFileManager should protect the data consistency by itself.

  2. Add a mutex, which will allow simultaneous reading/reading, but not simultaneous reading/writing or writing/writing.

Could you advice which option is more correct/adequate?


Solution

  • Per the same Apple document: "The methods of the shared FileManager object can be called from multiple threads safely." If you are using the 'shared FileManager object' (and not an instance), you have thread-safety built-in.