Clicky

iOS Dev Nugget 150 Using NSCoder to Persist Data

.

Need to run a code review on your codebase? Hire me

In Nugget #143 Don't Forget SQLite, we mentioned various ways of persisting data and pointed out SQLite as a very powerful tool for data storage. But besides storing natively types such as NSDictionary and NSString as plist, you can also store custom classes of your own by using subclasses of NSCoderNSKeyedUnarchiver and NSKeyedArchiver. You can archive objects into an NSData instance and unarchive from NSData instances. There's also convenience methods so you can do:

//Write to a file
[NSKeyedArchiver archiveRootObject:someObject toFile:aPath];

//Read from a file
NSObject* someObject = [NSKeyedUnarchiver unarchiveObjectWithFile:aPath];

You just need to make sure your own classes implement the methods -initWithCoder: and -encodeWithCoder: in the NSCoding protocol.

@implementation MyClass

//... other stuff

- (id)initWithCoder:(NSCoder*)decoder {
    if (self = [super init]) {
        self.property1 = [decoder decodeObjectForKey:@"property1"];
        self.property2 = [decoder decodeObjectForKey:@"property2"];
    }
    return self;
}

- (id)encodeWithCoder:(NSCoder*)encoder {
    [encoder encodeObject:self.property1 forKey:@"property1"];
    [encoder encodeObject:self.property2 forKey:@"property2"];
}

@end

With that you can do something like this to write an object (graph) to disk:

MyClass* obj;
//Set up obj
NSDictionary* aDict = @{@"someKey":obj}; 
[NSKeyedArchiver archiveRootObject:aDict toFile:aPath];

This is very useful if you want to persist small bits of objects that includes instances of your own classes. Handy for caching. Alternatively you can use NSKeyedArchiver to create NSData instances and save them in plists too.

Sponsored: Learn how to make money selling your own apps. Start your app publishing business: go to LearnAppMaking.com and sign up!


Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No

.

Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter

.

View archives of past issues