iOS常用数据类型转换集合

Home / iOS MrLee 2015-10-22 2721

不管做什么语言开发,经常会进行数据转换,如string转byte,string转int,byte数组转string....... 在iOS中也不例外,现在把这些都搜集在一起,方便参考。

iOS NSString 和NSData 转换

NSString 转换成NSData 对象
NSData* xmlData = [@"testdata" dataUsingEncoding:NSUTF8StringEncoding]; 

NSData 转换成NSString对象
NSData * data; 
NSString *result = [[NSString alloc] initWithData:data  encoding:NSUTF8StringEncoding]; 

NSData 转换成char*
NSData *data; 
char *test=[data bytes]; 

char* 转换成NSData对象
byte* tempData = malloc(sizeof(byte)*16); 
NSData *content=[NSData dataWithBytes:tempData length:16];

 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:0];
         return [documentsDirectory stringByAppendingPathComponent:filename];
 }
 
 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
     //音频文件路径
         NSString *mp3Path1 = [[NSBundle mainBundle] pathForResource:@"1" ofType:@"mp3"];
         NSString *mp3Path2 = [[NSBundle mainBundle] pathForResource:@"2" 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;
 }

 其他的转换函数

1、字符串拼接
NSString *newString = [NSString stringWithFormat:@"%@%@",tempA,tempB];

2、字符串转int
int intString = [newString intValue];

3、int转字符串
NSString *stringInt = [NSString stringWithFormat:@"%d",intString];

 

本文链接:https://www.it72.com/6528.htm

推荐阅读
最新回复 (0)
返回