OC基础 NSData

时间:2021-05-14 06:28:13

OC基础 NSData

1.NSString转NSData

        //NSString转NSData
NSString *string = @"abcd12345";
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"data = %@",data);

2.NSData转NSString

        //NSData转NSString
NSString *string1 = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"string1 = %@",string1);

3.NSData转换为UIImage

        //NSData转换为UIImage
NSData *imageData = [NSData dataWithContentsOfFile: imagePath];
UIImage *image = [UIImage imageWithData: imageData];

4.UIImage转换为NSData

         //UIImage转换为NSData
NSData *imageData = UIImagePNGRepresentation(image);

5.char * 转 NSData

        //char * 转 NSData
const char *string2 = "hello!";
NSData *data1 = [NSData dataWithBytes:string2 length:strlen(string2)+];
NSLog(@"data1 = %@,data1Length = %lu,data1Bytes = %s",data1,(unsigned long)[data1 length],[data1 bytes]);

6.bytes转NSData

        //bytes转NSData
NSData *data2 = [NSData dataWithBytes:[data1 bytes] length:strlen(string2)+];
NSLog(@"data2 = %@,data2Bytes = %s",data2,[data2 bytes]);

7.NSData转Byte

        //NSData转Byte
NSString *string3 = @"Byte";
NSData *data3 = [string3 dataUsingEncoding:NSUTF8StringEncoding];
Byte *byte = (Byte *)[data3 bytes];
NSLog(@"byte = %s",byte);

测试结果:

OC基础 NSData