Episode #7

Serializing Data to Disk

16 minutes
Published on March 15, 2012
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];

NSKeyedArchiver

// Bookmark.h

@interface Bookmark : NSObject <NSCoding>

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

@end
// 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];
}

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

// restoring the object
_bookmarks = [[NSKeyedUnarchiver unarchiveObjectWithFile:_path] retain];
Want more? Subscribers can view all 498 episodes. New episodes are released regularly.

Subscribe to get access →

Source Code

View on GitHub Download Source