Serializing Data to Disk

Episode #7 | 16 minutes | published on March 15, 2012
Free Video
It can be useful to save lightweight application data to disk so that it persists between application launches. This episode will show you how to serialize common objects such as NSArray and NSDictionary to disk, as well as implementing custom object serialization using NSKeyedArchiver.

Episode source code

Further Reading:

Property List Serialization

All values must be NSString, NSDate, NSNumber, NSData, NSDictionary, or NSArray. If you try to save an array with NSURL values, it will silently fail.

// writing to a file
NSArray *flavors = [NSArray arrayWithObjects:@"chocolate", @"vanilla", 
                              @"strawberry", nil];

[flavors writeToFile:PATH atomically:YES];

// reading from a file
NSArray *flavorsFromDisk = [NSArray arrayWithContentsOfFile:PATH];


// Bookmark.h

@interface Bookmark : NSObject <NSCoding>

@property (nonatomic, copy) NSString *label;
@property (nonatomic, copy) NSString *url;

// Bookmark.m
#import "Bookmark.h"

@implementation Bookmark

@synthesize label = _label;
@synthesize url = _url;

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super init];
    if (self) {
        self.label = [aDecoder decodeObjectForKey:@"label"];
        self.url = [aDecoder decodeObjectForKey:@"url"];

    return self;

- (void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:self.label forKey:@"label"];
    [aCoder encodeObject:self.url forKey:@"url"];

- (void)dealloc {
    [_label release];
    [_url release];
    [super dealloc];

// archiving the object
[NSKeyedArchiver archiveRootObject:_bookmarks toFile:_path];

// restoring the object
_bookmarks = [[NSKeyedUnarchiver unarchiveObjectWithFile:_path] retain];
blog comments powered by Disqus