Dec 2009
Reading & Writing Files on the iPhone
Accessing data, whether it be a from the iPhone’s memory or even from the internet is a necessity of almost any application. This article will overview some of the basics to access and saving files that your iPhone (or Mac) applition might need to do sometime or the other. The best
Directory Access
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil; NSString *filePath = [basePath stringByAppendingPathComponent:@"filename.plist"];
Using Plists
The Plist file format is the best format to use when reading and writing to the iPhone’s disk. Not only is it faster (because it is native) than XML, JSON and a plain text file to read, but the code is really simple.
NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfURL:filePath]; //or NSArray *array = [NSArray arrayWithContentsOfURL:filePath];
Then to save you data to a file:
// plistDict is a NSDictionary
NSString *error;
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
if(plistData) {
[plistData writeToFile:filePath atomically:YES];
} else {
NSLog(error);
[error release];
}
Play Nicely!
Where you save your files are important for when the iPhone backups information to a computer. You want to make sure your application backup is as small as possible so you need to place information in there specific directory.
- NSDocumentsDirectory- This data is backed up every time a user syncs their information to their computer.
- NSCachesDirectory – This information is not backed up by syncing, but not lost once your application quits. This space is ideally where you’d want to save state information. For example, in a text messaging application, you’d might want to save the string the user entered into the application, but had yet to sent out. You definitely don’t want to back this information up, but it will be needed when the application is opened again.
- NSTemporaryDirectory – This data is lost after your application is terminated.





