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

我用蓝牙发送 NSStringUIImage。我决定将两者都存储在 NSDictionary中,然后将字典转换为 NSData

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

132109 次浏览

来自 NSData 的 NSDictionary

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

NSDictionary to NSData

您可以使用 NSPropertyListSerialization 类来实现这一点:

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

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

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 的类执行此操作。

来源

NSDictionary-> NSData:

NSData *myData = [NSKeyedArchiver archivedDataWithRootObject:myDictionary];

NSData-> NSDictionary:

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

使用 NSJSONSerialization:

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


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

最新的返回 id,所以最好在强制转换后检查返回的对象类型(这里我强制转换为 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)

请试试这个

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