Answers:
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];
最新的return 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
。所以我尝试了您的代码。它不起作用。
来自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
。我为你改正了。