OS中编码转化
1.UTF-8转化
NSString *data = @"你好,北京!";
//转换成UTF-8
NSString *dataUTF8 = [data stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%@",dataUTF8);
//UTF-8转GBK,将UTF8代码替换,官方解释如下。
//Replaces all percent escapes with the matching characters as determined by the given encoding. Returns nil if the transformation is not possible (i.e. the percent escapes give a byte sequence not legal in the given encoding). See CFURLCreateStringByReplacingPercentEscapes in CFURL.h for more complex transformations
NSString *dataGBK = [dataUTF8 stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%@",dataGBK);
在Xcode4.2中执行结果如下:
发现NSString类中有内置的方法可以实现。他们分别是:
- (NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding
- (NSString *)stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)encoding