1,NSData 与 NSString
NSData --> NSString
NSString *aString = [[NSString alloc] initWithData:adata encoding:NSUTF8StringEncoding];
NSString --> NSData
NSString *aString = @"1234";
NSData *aData = [aString dataUsingEncoding: NSUTF8StringEncoding];
2,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,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23};
NSData *adata = [[NSData alloc] initWithBytes:byte length:24];
3,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);
4,NSData 与 NSMutableData
NSData --> MSMutableData
NSData *data=[[NSData alloc]init];
NSMutableData *mdata=[[NSMutableData alloc]init];
mdata=[NSData dataWithData:data];
5,NSData合并为一个NSMutableData
1 - (NSString *)filePathWithName:(NSString *)filename 2 { 3 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 4 NSString *documentsDirectory = [paths objectAtIndex:0]; 5 return [documentsDirectory stringByAppendingPathComponent:filename]; 6 } 7 8 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 9 //音频文件路径 10 NSString *mp3Path1 = [[NSBundle mainBundle] pathForResource:@"1" ofType:@"mp3"]; 11 NSString *mp3Path2 = [[NSBundle mainBundle] pathForResource:@"2" ofType:@"mp3"]; 12 //音频数据 13 NSData *sound1Data = [[NSData alloc] initWithContentsOfFile: mp3Path1]; 14 NSData *sound2Data = [[NSData alloc] initWithContentsOfFile: mp3Path2]; 15 //合并音频 16 NSMutableData *sounds = [NSMutableData alloc]; 17 [sounds appendData:sound1Data]; 18 [sounds appendData:sound2Data]; 19 //保存音频 20 21 NSLog(@"data length:%d", [sounds length]); 22 23 [sounds writeToFile:[self filePathWithName:@"tmp.mp3"] atomically:YES]; 24 25 [window makeKeyAndVisible]; 26 27 return YES; 28 }
6,NSString 合并
1 NSString* string; // 结果字符串 2 NSString* string1, string2; //已存在的字符串,需要将string1和string2连接起来 3 //方法1. 4 string = [NSString initWithFormat:@"%@,%@", string1, string2 ]; 5 //方法2. 6 string = [string1 stringByAppendingString:string2]; 7 //方法3 . 8 string = [string stringByAppendingFormat:@"%@,%@",string1, string2];