How can I convert NSDictionary to NSData and vice versa?

Ali picture Ali · Apr 1, 2011 · Viewed 125.6k times · Source

I am sending NSString and UIImage using bluetooth. I decided to store both in a NSDictionary and then convert the dictionary to NSData.

My question is how to convert NSDictionary to NSData and visa versa?

Answer

Anh Nguyen picture Anh Nguyen · Feb 18, 2013

NSDictionary -> NSData:

NSData *myData = [NSKeyedArchiver archivedDataWithRootObject:myDictionary];

NSData -> NSDictionary:

NSDictionary *myDictionary = (NSDictionary*) [NSKeyedUnarchiver unarchiveObjectWithData:myData];