NSData是用来包装数据的
NSData存储的是二进制数据,屏蔽了数据之间的差异,文本、音频、图像等数据都可用NSData来存储
NSData的用法
- NSString与NSData互相转换
//NSData-> NSString NSString *aString = [[NSString alloc] initWithData:adataencoding:NSUTF8StringEncoding];
//NSString->NSData NSString *aString = @"1234abcd";
NSData *aData = [aString dataUsingEncoding: NSUTF8StringEncoding];
将data类型的数据,转成UTF8的数据
+(NSString *)dataToUTF8String:(NSData *)data
{
NSString *buf = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
return [buf autorelease];
}
将string转换为指定编码
+(NSString *)changeDataToEncodinString:(NSData *)data encodin:(NSStringEncoding )encodin{
NSString *buf = [[[NSString alloc] initWithData:data encoding:encodin] autorelease];
return buf;
}
- 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];
- NSData与NSArray NSDictionary
+(NSString *)getLocalFilePath:(NSString *) fileName
{
return [NSString stringWithFormat:@"%@/%@%@", NSHomeDirectory(),@“Documents”,fileName];
}
包括将NSData写进Documents目录、从Documents目录读取数据
以及在进行网络数据通信的时候,经常会遇到NSData类型的数据。在该数据是dictionary结构的情况下,系统没有提供现成的转换成NSDictionary的方法,为此可以通过Category对NSDictionary进行扩展,以支持从NSData到NSDictionary的转换。声明和实现如下:
+(NSDictionary *)dictionaryWithContentsOfData:(NSData *)data {
CFPropertyListRef list = CFPropertyListCreateFromXMLData(kCFAllocatorDefault, (CFDataRef)data, kCFPropertyListImmutable, NULL);
if(list == nil) return nil;
if ([(id)list isKindOfClass:[NSDictionary class]]) {
return [(NSDictionary *)list autorelease];
}
else {
CFRelease(list);
return nil;
}
}