iPhone Developer Tips Visitor Stats: 122,631 Pageviews and 90,229 visitors in the past 30 days.
|
With just a few lines of code, you can read/write collections to/from files. The code below shows examples for writing and reading back both arrays and dictionaries.
Read and Write Collections to File
NSArray *array = [NSArray arrayWithObjects:
@"Hefeweizen", @"IPA", @"Pilsner", @"Stout", nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
array, @"array", @"Stout", @"dark", @"Hefeweizen", @"wheat", @"IPA",
@"hoppy", nil];
// Get path to documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
if ([paths count] > 0)
{
// Path to save array data
NSString *arrayPath = [[paths objectAtIndex:0]
stringByAppendingPathComponent:@"array.out"];
// Path to save dictionary
NSString *dictPath = [[paths objectAtIndex:0]
stringByAppendingPathComponent:@"dict.out"];
// Write array
[array writeToFile:arrayPath atomically:YES];
// Write dictionary
[dictionary writeToFile:dictPath atomically:YES];
// Read both back in new collections
NSArray *arrayFromFile = [NSArray arrayWithContentsOfFile:arrayPath];
NSDictionary *dictFromFile = [NSDictionary dictionaryWithContentsOfFile:dictPath];
for (NSString *element in arrayFromFile)
NSLog(@"Beer: %@", element);
for (NSString *key in dictFromFile)
NSLog(@"%@ Style: %@", key, [dictionary valueForKey:key]);
}
Verify the Output
The output in the console window for the above looks as follows:

Comments
3 Responses to “Read and Write Array, Dictionary and Other Collections to Files”
Leave Comment
Interesting, I was going to play with something similar in the next couple of weeks.
Q: If I now want to update the Array or Dictionary, would I instead use Mutable objects and simply call “writeToFile: xxxxxPath atomically:YES” (where xxxxx is array or dict)?
Thanks.
Hey Bill,
If I understand your question, yes, if you use mutable classes, I would think you could read into those objects, make changes, then write those same objects back to the system.
Hi Bill,
I’m using code similar to what you’ve written above. However, writeToFile returns NO when I try to write an array to a file, and the file remains empty.
I’ve used [[NSFileManager defaultManager] isWritableFileAtPath:locFilePath] to verify if the file exists, and is writable, which it is. I can also see the file in the file system using Finder. It is currently empty.
The array I’m trying to write is an array of dictionary objects.
Do you know if there’s a way I can troubleshoot this?
Many thanks,
Stephen C