我正在使用蓝牙发送NSString
和UIImage
。我决定将它们存储在NSDictionary
中,然后将字典转换为NSData
。
我的问题是如何将NSDictionary
转换为NSData
,反之亦然?
答案 0 :(得分:353)
NSDictionary - > NSData:
NSData *myData = [NSKeyedArchiver archivedDataWithRootObject:myDictionary];
NSData - >的NSDictionary:强>
NSDictionary *myDictionary = (NSDictionary*) [NSKeyedUnarchiver unarchiveObjectWithData:myData];
答案 1 :(得分:51)
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的任何类来执行此操作。
答案 2 :(得分:39)
使用NSJSONSerialization:
NSDictionary *dict;
NSData *dataFromDict = [NSJSONSerialization dataWithJSONObject:dict
options:NSJSONWritingPrettyPrinted
error:&error];
NSDictionary *dictFromData = [NSJSONSerialization JSONObjectWithData:dataFromDict
options:NSJSONReadingAllowFragments
error:&error];
最新返回id
,因此最好在投射后检查返回的对象类型(这里是我转换为NSDictionary)。
答案 3 :(得分:21)
在 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)
答案 4 :(得分:17)
来自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对象。
答案 5 :(得分:0)
请尝试这个
NSError *error;
NSDictionary *responseJson = [NSJSONSerialization JSONObjectWithData:webData
options:NSJSONReadingMutableContainers
error:&error];