头文件:
@interface NSString (OAURLEncodingAdditions) - (NSString *)URLEncodedString; - (NSString *)URLDecodedString; @end
m文件:
@implementation NSString (OAURLEncodingAdditions) - (NSString *)URLEncodedString{ NSString *result = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)self, NULL, CFSTR("!*'();:@&=+$,/?%#[]"), kCFStringEncodingUTF8); [result autorelease]; return result; } - (NSString*)URLDecodedString{ NSString *result = (NSString *)CFURLCreateStringByRepla cingPercentEscapesUsingE ncoding(kCFAllocatorDefault, (CFStringRef)self, CFSTR(""), kCFStringEncodingUTF8); [result autorelease]; return result; } @end
如果需要转换一个NSString, 只需要
NSString *temp = [@"测试utf8" URLEncodedString];
NSString *decoded = [temp URLDecodedString];
转自:http://borluse.wordpress.com/2011/01/28/一个比较方便的转换nsstring为utf8编码的函数/