12.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:

writeToFile

The path of the file to write to, as a string.

atomically

A 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 to YES when storing information that you don’t want to lose under any circumstance while your app is running.

encoding

Encoding of the text that you want to write to the path. Programmers usually use UTF8 for the encoding, using the NSUTF8StringEncoding constant value.

error

Takes a pointer to an NSError object so that if the saving operation fails, ...

Get iOS 6 Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.