O'Reilly logo

iOS 6 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required