I am sending NSString
and UIImage
using bluetooth. I decided to store both in a NSDictionary
and then convert the dictionary to
In Swift 2 you can do it in this way:
var dictionary: NSDictionary = ...
/* NSDictionary to NSData */
let data = NSKeyedArchiver.archivedDataWithRootObject(dictionary)
/* NSData to NSDictionary */
let unarchivedDictionary = NSKeyedUnarchiver.unarchiveObjectWithData(data!) as! NSDictionary
In Swift 3:
/* NSDictionary to NSData */
let data = NSKeyedArchiver.archivedData(withRootObject: dictionary)
/* NSData to NSDictionary */
let unarchivedDictionary = NSKeyedUnarchiver.unarchiveObject(with: data)
NSDictionary -> NSData:
NSData *myData = [NSKeyedArchiver archivedDataWithRootObject:myDictionary];
NSData -> NSDictionary:
NSDictionary *myDictionary = (NSDictionary*) [NSKeyedUnarchiver unarchiveObjectWithData:myData];
NSDictionary from NSData
http://www.cocoanetics.com/2009/09/nsdictionary-from-nsdata/
NSDictionary to NSData
You can use NSPropertyListSerialization class for that. Have a look at its method:
+ (NSData *)dataFromPropertyList:(id)plist format:(NSPropertyListFormat)format
errorDescription:(NSString **)errorString
Returns an NSData object containing a given property list in a specified format.
Please try this one
NSError *error;
NSDictionary *responseJson = [NSJSONSerialization JSONObjectWithData:webData
options:NSJSONReadingMutableContainers
error:&error];
NSDictionary -> NSData:
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:yourDictionary forKey:@"Some Key Value"];
[archiver finishEncoding];
[archiver release];
// Here, data holds the serialized version of your dictionary
// do what you need to do with it before you:
[data release];
NSData -> NSDictionary
NSData *data = [[NSMutableData alloc] initWithContentsOfFile:[self dataFilePath]];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
NSDictionary *myDictionary = [[unarchiver decodeObjectForKey:@"Some Key Value"] retain];
[unarchiver finishDecoding];
[unarchiver release];
[data release];
You can do that with any class that conforms to NSCoding.
source
Use NSJSONSerialization:
NSDictionary *dict;
NSData *dataFromDict = [NSJSONSerialization dataWithJSONObject:dict
options:NSJSONWritingPrettyPrinted
error:&error];
NSDictionary *dictFromData = [NSJSONSerialization JSONObjectWithData:dataFromDict
options:NSJSONReadingAllowFragments
error:&error];
The latest returns id
, so its a good idea to check the returned object type after you cast (here i casted to NSDictionary).