在进行网络数据通信的时候,经常会遇到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