如何将NSDictionary转换为NSData,反之亦然?

我使用蓝牙发送NSStringUIImage 。 我决定存储在一个NSDictionary ,然后将字典转换为NSData

我的问题是如何将NSDictionary转换为NSData ,反之亦然?

NSDictionary – > NSData:

 NSData *myData = [NSKeyedArchiver archivedDataWithRootObject:myDictionary]; 

NSData – > NSDictionary:

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

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]; 

你可以用任何符合NSCoding的类来做到这一点。

资源

使用NSJSONSerialization:

 NSDictionary *dict; NSData *dataFromDict = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error]; NSDictionary *dictFromData = [NSJSONSerialization JSONObjectWithData:dataFromDict options:NSJSONReadingAllowFragments error:&error]; 

最新的返回id ,所以它是一个好主意,检查返回的对象types后,你投(这里我铸造到NSDictionary)。

Swift 2中,你可以这样做:

 var dictionary: NSDictionary = ... /* NSDictionary to NSData */ let data = NSKeyedArchiver.archivedDataWithRootObject(dictionary) /* NSData to NSDictionary */ let unarchivedDictionary = NSKeyedUnarchiver.unarchiveObjectWithData(data!) as! NSDictionary 

Swift 3

 /* NSDictionary to NSData */ let data = NSKeyedArchiver.archivedData(withRootObject: dictionary) /* NSData to NSDictionary */ let unarchivedDictionary = NSKeyedUnarchiver.unarchiveObject(with: data) 

来自NSData的NSDictionary

http://www.cocoanetics.com/2009/09/nsdictionary-from-nsdata/

NSDictionary到NSData

你可以使用NSPropertyListSerialization类。 看看它的方法:

 + (NSData *)dataFromPropertyList:(id)plist format:(NSPropertyListFormat)format errorDescription:(NSString **)errorString 

以指定的格式返回包含给定属性列表的NSData对象。

请试试这个

 NSError *error; NSDictionary *responseJson = [NSJSONSerialization JSONObjectWithData:webData options:NSJSONReadingMutableContainers error:&error];