The iPhone provides a comprehensive set of operations for working with files and directories. NSFileManager includes methods for querying the contents of directories, creating, renaming and deleting contents, as well as getting/setting file attributes (readable, writeable, etc).
Point to the Documents Directory
Each application has its own sandbox in which you can read/write files. Files written to the sandbox are persistent across invocations of the application, including across application updates.
You can locate the Documents directory in the sandbox as shown below:
Creating a File
With the documents directory available, we can now use that path to create a new file in the sandbox and write a few lines of text:
We build a path to the file we want to create (file1.txt), initialize a string to write into the file, and write out the contents. The last line shows a directory listing of what is in the Documents directory after we create the file, see the figure below:
Renaming a File
To rename a file we move the file to a new path. The code below creates the destination path we are after, requests to move the file, and shows the Documents directory after the move.
After moving the file, the output should look similar to the image below:
Deleting a File
To round out this tip, let’s look at how to delete a file:
Once the file is deleted, as expected, the Documents directory is now empty:
These examples touch the surface of working with files. Check out the documentation forNSFileManager for all the specifics.