Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting NSDictionary object to NSData object and vice-versa

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?

like image 610
Ajayvictor007 Avatar asked Jul 01 '10 11:07

Ajayvictor007


People also ask

How do you convert NSDictionary to NSMutableDictionary?

Use -mutableCopy . NSDictionary *d; NSMutableDictionary *m = [d mutableCopy]; Note that -mutableCopy returns id ( Any in Swift) so you will want to assign / cast to the right type. It creates a shallow copy of the original dictionary.

What is NSData?

NSData provides methods for atomically saving their contents to a file, which guarantee that the data is either saved in its entirety, or it fails completely. An atomic write first writes the data to a temporary file and then, only if this write succeeds, moves the temporary file to its final location.

What is NSDictionary in Swift?

An object representing a static collection of key-value pairs, for use instead of a Dictionary constant in cases that require reference semantics.


1 Answers

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];
like image 89
Robert Redmond Avatar answered Sep 21 '22 12:09

Robert Redmond