Saving and Reading Files
To save or read a simple file, you are likely to use one of the convenience methods for the class appropriate to the file’s contents. NSString, NSData, NSArray, and NSDictionary provide writeToURL... and initWithContentsOfURL... methods.
NSString and NSData objects map directly between their own contents and the contents of the file. Here, I’ll generate a text file from a string:
NSError* err = nil;
BOOL ok =
[@"howdy" writeToURL:[myfolder URLByAppendingPathComponent:@"file1.txt"]
atomically:YES encoding:NSUTF8StringEncoding error:&err];
// error-checking omittedNSArray and NSDictionary files are actually property lists (Chapter 10), and will work only if all the contents of the array or dictionary are property list types (NSString, NSData, NSDate, NSNumber, NSArray, and NSDictionary).
So how do you save to a file an object of some other class? Well, if an object’s class adopts the NSCoding protocol, you can convert it to an NSData and back again using NSKeyedArchiver and NSKeyedUnarchiver; an NSData can then be saved as a file or in a property list. An example of doing this with a UIColor object appears in Chapter 10.
You can make your own class adopt the NSCoding protocol. This can become somewhat complicated because an object can refer (through an instance variable) to another object, which may also adopt the NSCoding protocol, and thus you can end up saving an entire graph of interconnected objects if you wish. However, I’ll confine myself to illustrating ...
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