Objective-C 数据类型转换

1.NSDictionary转NSData【相互转换】

NSDictionary *dic= @{@"name":@"macRong",@"webHome":@"eqi.cc"}; 
NSData *data= [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil]; 
NSDictionary *dictionary =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
 NSLog(@"NSDictionary转NSData= %@",data); 
NSLog(@"NSData转NSDictionary=%@",dictionary);

2.NSDictionary转NSString(需要先将NSDictionary转为NSData,再转为NSString)

NSDictionary *dictionary2 = [NSDictionary dictionaryWithObjectsAndKeys:_userNameTexField.text,@"AAccount", _pwdTextField.text,@"APassword",@"1",@"DeviceType",nil]; 
NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary2 options:NSJSONWritingPrettyPrinted error:nil]; 
NSString *strhh = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];

3.NSData和NSString相互转换

// 字符串转Data
NSString *str =@"jesfds"; 
NSData *data =[str dataUsingEncoding:NSUTF8StringEncoding];
//NSData 转NSString
NSString *result  =[[ NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

4.判断字符串中含有某个字符串

//判断userNameLab.text 是否含有bendan
if([userNameLab.text rangeOfString:@"bendan"].location !=NSNotFound)//userNameLab
{
       NSLog(@"yes");
}else {
     NSLog(@"no");
}

5.UIImage和NSData

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

6.Int 和NSNumber

//int 转NSNumber
int myInt;
NSNumber *myNumber = [NSNumber numberWithInt:myInt];
//NSNumber 转int
int myInt = [myNumber intValue];

7.int转string

int number = 100;
NSString *string = [[NSString alloc] initWithFormat:@"%d",number];

你可能感兴趣的:(Objective-C 数据类型转换)