converting NSDictionary object to NSData object and vice-versa

Ajayvictor007 picture Ajayvictor007 · Jul 1, 2010 · Viewed 12.6k times · Source

I have to convert an NSDictionary object into NSData and further I have to get the same NSDictionary out of the NSData object. How should I go about it?

Answer

Robert Redmond picture Robert Redmond · Jul 1, 2010

use NSKeyedArchiver

To convert NSDictionary To NSData

NSMutableData *data = [[NSMutableData alloc]init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
[archiver encodeObject:YOURDICTIONARY forKey: YOURDATAKEY];
archiver finishEncoding];
[data writeToFile:YOURFILEPATH atomically:YES];
[data release];
[archiver release];

To get the NSDictionary back from the stored NSData

NSData *data = [[NSMutableData alloc]initWithContentsOfFile:YOURFILEPATH];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
YOURDICTIONARY = [unarchiver decodeObjectForKey: YOURDATAKEY];
[unarchiver finishDecoding];
[unarchiver release];
[data release];