iPhone 101
Code Tips
Resources
More
Objects that conform to the NSCoding protocol can be saved to (and read from) a file using the NSKeyedArchiver class.
NSCoding
Many common Objective-C classes already conform to NSCoding. You can save objects of any of these types without doing anything special:
NSArray
NSData
NSDate
NSDictionary
NSNumber
NSString
If you aren't sure whether a class supports NSCoding, check its class documentation.
For custom classes, you must add the encodeWithCoder: and initWithCoder: methods to your class to conform to the NSCoding protocol. Example
Saving Data
Here's an example of saving a dictionary object to a file. Add your own data objects as key/value pairs in the dataDict. This method goes in your App Delegate:
- (void) saveData { NSMutableDictionary *dataDict = [[NSMutableDictionary alloc] initWithCapacity:3]; if (games != nil) { [dataDict setObject:games forKey:@"games"]; // save the games array } NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectoryPath = [paths objectAtIndex:0]; NSString *filePath = [documentsDirectoryPath stringByAppendingPathComponent:@"appData"]; [NSKeyedArchiver archiveRootObject:dataDict toFile:filePath]; }
To save data, add a call to [self saveData] to the applicationWillTerminate: and applicationWillResignActive: methods. You may also want to save data whenever significant data changes happen (such as adding new items to an array, or creating new objects that need to be saved).
Loading Data
To load your saved data, add the following to the app delegate's didFinishLaunchingWithOptions:
// look for saved data. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectoryPath = [paths objectAtIndex:0]; NSString *filePath = [documentsDirectoryPath stringByAppendingPathComponent:@"appData"]; if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) { NSData *data = [NSData dataWithContentsOfFile:filePath]; NSDictionary *savedData = [NSKeyedUnarchiver unarchiveObjectWithData:data]; if ([savedData objectForKey:@"games"] != nil) { self.games = [[NSMutableArray alloc] initWithArray:[savedData objectForKey:@"games"]]; } }
NOTE: The data retrieved from the savedData dictionary will be immutable. If your object is a mutable class, you should create it using a copy of the saved data object.
Be sure to use the same filePath that you used in the saveData method.
Additional References
- NSCoding
- NSKeyedArchiver Class Reference