将NSDictionary对象转换为NSData对象,反之亦然

时间:2010-07-01 11:39:22

标签: ios objective-c nsdictionary nsdata

我必须将NSDictionary对象转换为NSData,并且我必须从NSDictionary对象中获取相同的NSData。我应该怎么做呢?

2 个答案:

答案 0 :(得分:32)

使用NSKeyedArchiver

将NSDictionary转换为NSData

NSMutableData *data = [[NSMutableData alloc]init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
[archiver encodeObject:YOURDICTIONARY forKey: YOURDATAKEY];
archiver finishEncoding];
[data writeToFile:YOURFILEPATH atomically:YES];
[data release];
[archiver release];

从存储的NSData中取回NSDictionary

NSData *data = [[NSMutableData alloc]initWithContentsOfFile:YOURFILEPATH];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
YOURDICTIONARY = [unarchiver decodeObjectForKey: YOURDATAKEY];
[unarchiver finishDecoding];
[unarchiver release];
[data release];

答案 1 :(得分:2)

罗伯特回答的一个更简单的版本:

[NSKeyedArchiver archiveRootObject:YOURDICTIONARY toFile:YOURFILEPATH];

而且,相应地:

YOURDICTIONARY = [NSKeyedUnarchiver unarchiveObjectWithFile:YOURFILEPATH];

或者回答最初设置的问题,而不将文件归入事物:

NSData *data = [NSKeyedArchiver archivedDataWithRootObject:YOURDICTIONARY];
...
YOURDICTIONARY = [NSKeyedUnarchiver unarchiveObjectWithData:data];

它是所有工厂方法,所以无论是否有ARC都是相同的代码;所使用的方法自OS X v10.2以来就已经可用,并且从第一天起就在iOS上可用。