14.2. Writing to and Reading from Files
Problem
You want to be able to save information to disk (e.g., text, data, images, etc.).
Solution
Cocoa classes that allow you to store information, such as
NSString, UIImage, and NSData, all expose instance methods that allow
you to store their data to disk under a given path.
Discussion
In order to store text to disk, assuming that your text is
stored in an instance of NSString (or
the immutable version of this class), you can use the writeToFile:atomically:encoding:error: instance method of
this class. This method works with strings that represent the
destination path. Here are the different parameters:
writeToFileThe path of the file to write to, as a string.
atomicallyA Boolean that, if set to
YES, will first write the file to a temporary space and will then move the temporary file to the destination that you chose. This will ensure that the contents of the file will be saved to disk first and then saved to its destination, so that if iOS crashes before the file is saved to the final destination, your contents will still be saved later when the OS is back up again. It is recommended to set this value toYESwhen storing information that you don’t want to lose under any circumstance while your app is running.encodingEncoding of the text that you want to write to the path. Programmers usually use UTF8 for the encoding, using the
NSUTF8StringEncodingconstant value.errorTakes a pointer to an
NSErrorobject so that if the saving operation fails, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access