首页 > 代码库 > NSDictionary和NSData之间的相互转换
NSDictionary和NSData之间的相互转换
我封装好了2个方法,用来字典和data相互转换的,直接复制方法拿来用就可以了,注意2点:
1.我是用的mrc,用arc的同学把autorelease去掉即可。
2.第二个我是路径文件转的字典,想data转的话自己把方法改一下就行了。
//字典转data
+(NSData *)returnDataWithDictionary:(NSDictionary *)dict
{
NSMutableData * data = http://www.mamicode.com/[[NSMutableDataalloc] init];
NSKeyedArchiver * archiver = [[NSKeyedArchiveralloc] initForWritingWithMutableData:data];
[archiverencodeObject:dict forKey:@"talkData"];
[archiverfinishEncoding];
[dataautorelease];
[archiverautorelease];
return data;
}
//路径文件转dictonary
+(NSDictionary *)returnDictionaryWithDataPath:(NSString *)path
{
NSData * data = http://www.mamicode.com/[[NSMutableDataalloc] initWithContentsOfFile:path];
NSKeyedUnarchiver * unarchiver = [[NSKeyedUnarchiveralloc] initForReadingWithData:data];
NSDictionary * myDictionary = [[unarchiver decodeObjectForKey:@"talkData"] retain];
[unarchiverfinishDecoding];
// NSLog(@"%@", myDictionary);
[unarchiverautorelease];
[dataautorelease];
return myDictionary;
}
NSDictionary和NSData之间的相互转换