Sunday, September 18, 2011

Xcode snippet #2: Archiving objects with NSKeyedArchiver

Archiving objects with NSKeyedArchiver is the process of saving your objects to a binary file. This process is called encoding. In this step-by-step tutorial we will persist a settings object to a file, and bring it back to life using NSKeyedUnArchiver. Archiving objects is very convenient way for saving small amounts of data like settings in your iPhone app.

Step 1: Comply with the NSCoding protocol
The first thing we have to do is to let our object comply with the NSCoding protocol. This protocol adds encoding and decoding methods to our object. Complying is easily done by adding to the object like this:
@interface Settings : NSObject<NSCoding> {
}
Step 2: Implement the encodeWithCode and initWithCoder methods
We have to tell the NSKeyedArchiver object how our object should be encoded. Simply said tell it what our properties are and what types they are etc.

This is done the encodeWithCoder method (as implemented by the NSCoding protocol), here under you see an example for an object, boolean and int property.
- (void)encodeWithCoder:(NSCoder *)coder {
        [coder encodeObject:self.name forKey:@"name"];
	[coder encodeBool:self.newsLetter forKey:@"newsLetter"];
	[coder encodeInt32:self.count forKey:@"count"];    
}

To unarchive our object we have to implement the initWithCoder method: (Make sure that the keys in both the encodeWithCoder and initWithCoder are the same for each property)

-(id)initWithCoder:(NSCoder *)coder {
	if ((self = [super init]))
	{
          self.name = [[coder decodeObjectForKey:@"name"] retain];  
          self.newsLetter = [coder decodeBoolForKey:@"newsLetter"]; 
          self.count = [coder decodeInt32ForKey:@"count"];    
 	}
	return self;
}

That is pretty much all we have to do before we can archive and unarchive.

Step 3: Implement the archive and unarchive methods
What is left is to make two methods for un- and archiving. The saveSetting methods has two parameters, namely settings, the object to archive and the name for the file we want to save it to. With help of the getFullFilePath method we get a full file path to the Document directory of our device. To bring our object back to live use the loadSettings method.
-(NSString*) getFullFilePath:(NSString*)name
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains
       (NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *savePath = [paths objectAtIndex:0];
    NSString *theFileName = [NSString stringWithFormat:@"%@.setting", name];   
    return [savePath stringByAppendingPathComponent: theFileName];
}

-(void)saveSetting:(Settings *)settings name: (NSString *)name
{
    NSString *filePath = [self getFullFilePath:name];
    NSData *theData = [NSKeyedArchiver archivedDataWithRootObject:settings];
    [NSKeyedArchiver archiveRootObject:theData toFile:filePath]; 
}

-(Settings*)loadSetting:(NSString *)name 
{
    NSString *filePath = [self getFullFilePath:name];
    
    NSData *theData = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
    Settings *settings = [NSKeyedUnarchiver unarchiveObjectWithData:theData];
    return settings; 
    
}
Saving arrays of objects
It is also very easy to save lists of objects to file. Suppose we have a list with Settings and want to store them in one file. You can achieve this by archiving a NSMutableArray. For example:
// Archiving
NSMutableArray *array = self.self.settingsList;
[NSKeyedArchiver archiveRootObject:array toFile:
                      [savePath stringByAppendingPathComponent: theFileName]];

//UnArchiving
NSMutableArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:
                      [savePath stringByAppendingPathComponent: theFileName]];
if ([array count] > 0) {
    self.settingsList = array;
    }

Conclusion, the NSKeyedArchiver and NSKeyedUnarchiver are pretty easy and straight forwarded to use for persisting objects. It is very handy for saving small objects likes settings etc.
More information:
NSKeyedArchiver Class Reference
NSCoding protocol reference