NSString / NSData / char* 类型之间的转换


NSString / NSData / char* 类型之间的转换

  • NSString 转化为 char *
1
2
NSString * str= @“Test”;
const char * a =[str UTF8String];
  • char * 转化为 NSString
1
NSString *str=[NSString stringWithCString  encoding:NSUTF8StringEncoding];
  • char * 转化 NSData
1
2
3
4
5
6
方法一:
char * a = (char*)malloc(sizeof(byte)*16);
NSData *data = [NSData dataWithBytes: a length:strlen(a)];
方法二:
转换为NSString: - (id)initWithUTF8String:(const char *)bytes
然后用NSString的 - (NSData *)dataUsingEncoding:(NSStringEncoding)encoding
  • NSData 转化 char *
1
2
NSData data ;
char* a=[data bytes];
  • NSData 转化 NSString;
1
2
NSData* data;
NSString* aStr= [NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
  • NSString 转化 NSData
1
NSData* xmlData = [@"testdata" dataUsingEncoding:NSUTF8StringEncoding];
  • NSString 转化 NSURL
1
2
//NSURL *url = [NSURL URLWithString:[str   stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding ]]; 
NSString *urlString=[@"http://www.google.com/search?client=safari&rls=en&q=搜索&ie=UTF-8&oe=UTF-8" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  • NSURL 转化 NSString
1
2
NSURL *url=[NSURL URLWithString:urlString];
NSString *s=[[url absoluteString] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];