首页 > 代码库 > NSData转换成NSDictionary
NSData转换成NSDictionary
在进行网络数据通信的时 候,经常会遇到NSData类型的数据。在该数据是dictionary结构的情况下,系统没有提供现成的转换成NSDictionary的方法,为此可 以通过Category对NSDictionary进行扩展,以支持从NSData到NSDictionary的转换。声明和实现如下:
@interface NSDictionary (Helpers)
+ (NSDictionary *)dictionaryWithContentsOfData:(NSData *)data;
@end
@implementation NSDictionary (Helpers)
+ (NSDictionary *)dictionaryWithContentsOfData:(NSData *)data {
CFPropertyListRef plist = CFPropertyListCreateFromXMLData(kCFAllocatorDefault, (CFDataRef)data,
kCFPropertyListImmutable,
NULL);
if(plist == nil) return nil;
if ([(id)plist isKindOfClass:[NSDictionary class]]) {
return [(NSDictionary *)plist autorelease];
}
else {
CFRelease(plist);
return nil;
}
}
@end
@interface NSDictionary (Helpers)
+ (NSDictionary *)dictionaryWithContentsOfData:(NSData *)data;
@end
@implementation NSDictionary (Helpers)
+ (NSDictionary *)dictionaryWithContentsOfData:(NSData *)data {
CFPropertyListRef plist = CFPropertyListCreateFromXMLData(kCFAllocatorDefault, (CFDataRef)data,
kCFPropertyListImmutable,
NULL);
if(plist == nil) return nil;
if ([(id)plist isKindOfClass:[NSDictionary class]]) {
return [(NSDictionary *)plist autorelease];
}
else {
CFRelease(plist);
return nil;
}
}
@end
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。