如何将NSDictionary转换为NSData,以及如何反向转换?

162
我正在使用蓝牙发送NSStringUIImage。我决定将它们都存储在一个NSDictionary中,然后将该字典转换为NSData

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

6个回答

369

NSDictionary -> NSData:

NSData *myData = [NSKeyedArchiver archivedDataWithRootObject:myDictionary];

NSData -> NSDictionary:

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

对于NSData转NSDictionary,将其强制转换为NSDictionary似乎是不必要的。 - Pang

52

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协议的任何类来完成这个任务。

来源


1
不是要贬低这个答案,但提醒一下它并不符合ARC标准。 - Madbreaks
10
是的,我的答案是来自2011年,当时ARC不存在。 - LeonS

46

使用NSJSONSerialization:

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

NSDictionary *dictFromData = [NSJSONSerialization JSONObjectWithData:dataFromDict
                                                             options:NSJSONReadingAllowFragments
                                                               error:&error];

最新返回的是 id,所以在您强制转换后(这里我强制转换为NSDictionary),检查返回对象类型是一个好主意。


24

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)

无法工作!Swift 3等效代码无法工作。 let data = NSKeyedArchiver.archivedData(withRootObject: dataFromNetwork)[_SwiftValue encodeWithCoder:]:向实例发送未识别的选择器... - mythicalcoder
感谢您的快速回复。我的意思是这样的 - Swift 3代码也不起作用。我的数据来自3lvis/networking HTTP库,它是Any?类型的。但它显示将NSDictionary转换为NSData时出错。所以我尝试了你的代码。但还是没有成功。 - mythicalcoder

19

从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对象,其中包含以指定格式表示的给定属性列表。


这是大多数Mac OS开发者的非常优雅的解决方案。 - mjl007

0
请尝试这个。
NSError *error;
NSDictionary *responseJson = [NSJSONSerialization JSONObjectWithData:webData
                                options:NSJSONReadingMutableContainers
                                error:&error];

这是response,而不是responce。我已经为您更正了。 - Alex Zavatone

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接