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

7 comments:

Anonymous said...

Thx for the clear explanation. AND...
how do I delete/eliminate old archive files I no longer need. I think they would eventually clutter up the iPhone storage.

paperwritingservice.ninja said...

It helped to clear up some cluttering at my device. Thanks a lot for landing a sympathetic ear and giving a hand of help!

Anonymous said...

I cannot thank Mr Benjamin service enough and letting people know how grateful I am for all the assistance that you and your team staff have provided and I look forward to recommending friends and family should they need financial advice or assistance @ 1,9% Rate for Business Loan .Via Contact : .  lfdsloans@outlook.com. WhatsApp...+ 19893943740. Keep up the great work.
Thanks, Busarakham.

Mahil mithu said...

Well, I really appreciated for your great work. This topic submitted by you is helpful and keep sharing...
Separation Before Divorce
Divorce Without Separation Agreement

xcode in windows said...

Before we get into how to use XCode on Windows, we should first define XCode. So XCode is an Integrated Development Environment (IDE), which is essentially a very powerful piece of software used to create Mac apps. If you intend to design programmes for the Mac OS, you should be aware that XCode is an Apple-created toolset that will help you get there. Designing apps for Windows is a far more doable effort because you can accomplish it on any platform. However, if you want to create Apple applications, XCode is essential.

Anonymous said...

You have shared really very nice information. Please keep posting like this so that we can get knowledge from your blog. I hope I will read your new blog soon.
OTM Training

ISO In Saudi Arabia said...

Bravo to the author for not just addressing a complex topic, but for making it accessible and clear. The breakdown into smaller, understandable segments really worked for me. I’m walking away with a newfound confidence—thanks for making it all so understandable! Visit our link for ISO 9001 Certification In Saudi Arabia


Use an image as your UIBarButtonItem

Using an image as your UIBarButtonItem in your navigationcontroller bar can only be achieved by using a common UIButton as the BarButtonItem...