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

8 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!

Anong Busarakham 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.

Gaurav Sharma said...

Good blog informatve for readers such a nice content keep posting thanks for sharing
Best Hotel in Mussoorie
business news in hindi
CHOPTA – “Mini Switzerland of Uttrakhand"
TOP 20 HILL STATIONS OF INDIA

Data Science Programs said...

I was very happy to find this site. I really enjoyed reading this article today and think it might be one of the best articles I have read so far. I wanted to thank you for this excellent reading !! I really enjoy every part and have bookmarked you to see the new things you post. Well done for this excellent article. Please keep this work of the same quality.
Data Science Course in Bangalore

Yunita wijaya said...

SUPER BIG PROMO DI SITUS SAHABAT KARTU
=============================================
Hai Teman - Teman Smuanya, Yang Hobi Bermain Judi Online
Anda Merasa Capek, DEPOSIT Teruss..Tapi Tidak Pernah Withdraw ?
=============================================
Nikmati Seluruh Game Berkualitas & Raih Kemenangan Anda Di SAHABAT KARTU!!
Game Yang di Hadirkan SAHABAT KARTU Yaitu :
* Poker Online
* BandarQ
* Domino99
* Bandar Sakong
* Sakong
* BANDAR66
* AduQ
* Sakong
* Perang Baccarat
* Perang Dadu
==========================================
SPECIAL PROMO KHUSUS MEMBER SETIA SAHABAT KARTU
- Minimal DP & WD Cuma Rp. 20.000
- BONUS CASHBACK 0.5% ( Setiap Hari Senin )
- REFERRAL 20% ( Seumur Hidup )
- 100% NON ROBOT & 100% TANPA ADMIN BERMAIN
- 100% GAMPANG MENANG
- JACKPOT HARIAN HINGGA JUTA RUPIAH
- MENERIMA DEPOSIT VIA PULSA TSEL
======================================
AKSES KAMI DI LINK RESMI :
- jpsahabatkartu.org
- jpsahabatkartu.info
- jpsahabatkartu.net
- jpsahabatkartu.com
=====================
* Livechat : SAHABAT KARTU
* LINE : Cs_sahabatkartu
* Whatsapp : +855886427216

Sahabatkartu: Situs Poker Online, DominoQQ, Domino99, BandarQ Terpercaya

stevanie said...

sdomino99.org Merupakan Salah Satu Situs yang terpercaya Di Indonesia
dominowin99 Memiliki Permainan Yang Mudah Dimainkan & 100% Mudah Menang Lohh..
Cukup Dengan 1 USER ID Anda Bisa Bermain 10 GAME Berkualitas :
* Poker
* Domino99
* AduQ
* Capsa Susun
* Sakong
* Bandar Poker
* BANDARQ ONLINE
* BANDAR66 ONLINE
* Perang Baccarat
* Perang Dadu ( New Game )
+++++++++++++++++++++++++++++++
AKSES LINK ALTERNATIF TERBARU :
- sdomino99.com
- sdomino99net
- sdomino99.org
- sdomino99.info

< Contact Us >
Info Lebih Lanjut Hubungi :
W.A : +6285974599065


Sahabatdomino : Situs QQ Online, Agen Domino99 dan BandarQ Online Terbesar Di Asia

Rajabandarq said...

Agen bandarq
Agen bandarq
Agen bandarq
Agen bandarq
Agen bandarq
Agen bandarq
Agen bandarq
Agen bandarq
Agen bandarq
Agen bandarq

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...