简介
NSData是用来包装数据的,NSData存储的是二进制数据,屏蔽了数据之间的差异,文本、音频、图像等数据都可用NSData来存储。在多媒体开发时,比较常用,例如拼接音频、图片。
用法
-
NSString
与NSData
NSString -> NSData
NSString *aString = @"1234abcd";
NSData *aData = [aString dataUsingEncoding: NSUTF8StringEncoding];
NSData -> NSString
NSString *aString = [[NSString alloc] initWithData:adata encoding:NSUTF8StringEncoding]; -
NSData
与Byte
NSData -> Byte
NSString *testString = @"1234567890";
NSData *testData = [testString dataUsingEncoding: NSUTF8StringEncoding];
Byte *testByte = (Byte *)[testData bytes];
Byte --> NSData
Byte byte[] = {0,1,2,3,4,5,6,7};
NSData *adata = [[NSData alloc] initWithBytes:byte length:8]; -
NSData
与UIImage
NSData --> UIImage
UIImage *aImage = [UIImage imageWithData: imageData];
//例:从本地文件沙盒中取图片并转换为NSData
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *name = [NSString stringWithFormat:@"ceshi.png"];
NSString *finalPath = [path stringByAppendingPathComponent:name];
NSData *imageData = [NSData dataWithContentsOfFile: finalPath];
UIImage *aimage = [UIImage imageWithData: imageData];
UIImage-> NSData
NSData *imageData = UIImagePNGRepresentation(aimae); -
NSData
与NSMutableData
NSData --> MSMutableData
NSData *data=[[NSData alloc]init];
NSMutableData *mData=[[NSMutableData alloc]init];
mData=[NSData dataWithData:data];
注意
在进行网络数据通信的时候,经常会遇到NSData类型的数据。在该数据是dictionary结构的情况下,系统没有提供现成的转换成NSDictionary的方法,为此可以通过Category对NSDictionary进行扩展,以支持从NSData到NSDictionary的转换。声明和实现如下:
+ (NSDictionary *)dictionaryWithContentsOfData:(NSData *)data{ NSDictionary *content = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:NULL]; return content; }