Skip to content

Instantly share code, notes, and snippets.

@subdigital
Created March 11, 2012 19:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save subdigital/2017689 to your computer and use it in GitHub Desktop.
Save subdigital/2017689 to your computer and use it in GitHub Desktop.
Property List Serialization
// 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];
// 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];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment