(转)Object-C 中各数据类型转换 NSData转NSString,Byte,UIImage

时间:2024-07-03 19:33:38
,NSData 与 NSString
  NSData --> NSString
  NSString *aString = [[NSString alloc] initWithData:adata encoding:NSUTF8StringEncoding];
  NSString --> NSData
  NSString *aString = @"";
  NSData *aData = [aString dataUsingEncoding: NSUTF8StringEncoding]; ,NSData 与 Byte
  NSData --> Byte
  NSString *testString = @"";
  NSData *testData = [testString dataUsingEncoding: NSUTF8StringEncoding];
  Byte *testByte = (Byte *)[testData bytes];
  Byte --> NSData
  Byte byte[] = {,,,,,,,,,,,,,,,,,,,,,,,};
  NSData *adata = [[NSData alloc] initWithBytes:byte length:]; ,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合并为一个NSMutableData - (NSString *)filePathWithName:(NSString *)filename
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:];
return [documentsDirectory stringByAppendingPathComponent:filename];
} - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//音频文件路径
NSString *mp3Path1 = [[NSBundle mainBundle] pathForResource:@"" ofType:@"mp3"];
NSString *mp3Path2 = [[NSBundle mainBundle] pathForResource:@"" ofType:@"mp3"];
//音频数据
NSData *sound1Data = [[NSData alloc] initWithContentsOfFile: mp3Path1];
NSData *sound2Data = [[NSData alloc] initWithContentsOfFile: mp3Path2];
//合并音频
NSMutableData *sounds = [NSMutableData alloc];
[sounds appendData:sound1Data];
[sounds appendData:sound2Data];
//保存音频 NSLog(@"data length:%d", [sounds length]); [sounds writeToFile:[self filePathWithName:@"tmp.mp3"] atomically:YES]; [window makeKeyAndVisible]; return YES;
}