converting NSDictionary object to NSData object and vice-versa

谁说我不能喝 提交于 2019-11-26 15:39:07

问题


I have to convert an NSDictionary object into NSData and further I have to get the same NSDictionary out of the NSData object. How should I go about it?


回答1:


use NSKeyedArchiver

To convert NSDictionary To 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];

To get the NSDictionary back from the stored NSData

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



回答2:


A much simpler version of Robert's answer:

[NSKeyedArchiver archiveRootObject:YOURDICTIONARY toFile:YOURFILEPATH];

And, correspondingly:

YOURDICTIONARY = [NSKeyedUnarchiver unarchiveObjectWithFile:YOURFILEPATH];

Or to answer the question as originally set, without imputing a file into things:

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

It's all factory methods so it's the same code with or without ARC; the methods used have been available since OS X v10.2 and on iOS since day one.



来源:https://stackoverflow.com/questions/3157356/converting-nsdictionary-object-to-nsdata-object-and-vice-versa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!