iOS-NSData与NSDictionary的互相转换

这里,将字典转换成NSData类型。有一点必须注意的,必须实现

- (id)initWithCoder:(NSCoder *)aDecoder方法和

- (void)encodeWithCoder:(NSCoder *)aCoder方法。

 

 

+ (NSData *)returnDataWithDictionary:(NSDictionary*)dict

{

    NSMutableData* data = [[NSMutableData alloc]init];

    NSKeyedArchiver* archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];

    [archiver encodeObject:dict forKey:@"talkData"];

    [archiver finishEncoding];

    return data;

}

将字典路径的字符串转换为字典 

+ (NSDictionary *)returnDictionaryWithDataPath:(NSString*)path

{

    NSData* data = [[NSMutableData alloc]initWithContentsOfFile:path];

    NSKeyedUnarchiver* unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:data];

    NSDictionary* myDictionary = [unarchiver decodeObjectForKey:@"talkData"];

    [unarchiver finishDecoding];

   

    return myDictionary;

}

posted on 2015-11-17 23:10  XHShare  阅读(1218)  评论(0编辑  收藏  举报

导航