我正在使用蓝牙发送
NSString
和UIImage
。我决定将它们都存储在一个NSDictionary
中,然后将该字典转换为NSData
。
我的问题是如何将NSDictionary
转换为NSData
,反之亦然?
NSString
和UIImage
。我决定将它们都存储在一个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];
使用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)
Any?
类型的。但它显示将NSDictionary
转换为NSData
时出错。所以我尝试了你的代码。但还是没有成功。 - mythicalcoder从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];
response
,而不是responce
。我已经为您更正了。 - Alex Zavatone