iOS NSData简单解析

iOS 基本数据类型之NSData
1 nsdata
作用:
用于存储二进制的数据类型
nadat类提供一种简单的方式,它用来设置缓存区。将文件的内容读入到缓存区。或者将缓存区中的内容写到一个文件。
不变缓存区(nsdata类) 也可定义可变缓存区类(nsmutableData类)

NSData 、 NSString互转:
    NSData * data = [str dataUsingEncoding:NSUTF8StringEncoding]; //NSString转换成NSData类型
    NSString * newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  NSData 、Byte 互转
    NSString *testString = @"1234567890";
    NSData *testData = [testString dataUsingEncoding: NSUTF8StringEncoding];
    Byte *testByte = (Byte *)[testData bytes];
    Byte byte[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23};
    NSData *adata = [[NSData alloc] initWithBytes:byte length:24];
  NSData转UIImage
    UIImage *aimage = [UIImage imageWithData: data];
  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
NSData 应用场景
将文件的内容读入内存缓冲区
    NSData *fileData;
    NSFileManager *fileManager = [[NSFileManager alloc]init];
    fileData = [fileManager contentsAtPath:path];
  将缓冲区的内容写入到一个文件中
    NSFileManager *fileManager = [[NSFileManager alloc]init];
    [fileManager createFileAtPath:path contents:fileData attributes:nil];
天下文章一大抄 该文内容根据以下博客整理
http://www.cnblogs.com/GISerYang/p/3345350.html
http://bj007.blog.51cto.com/1701577/538990/
http://blog.csdn.net/jerryvon/article/details/7350567
http://www.cnblogs.com/duchengdong/archive/2012/03/29/2422997.html
http://www.myexception.cn/operating-system/1808379.html

上一篇:Android5.0以下drawable tag vector错误的解决办法(转发)


下一篇:ANdroid5.0不能隐式启动service,必须显示,解决办法,加服务端包名