iOS NSString 转换为UTF-8编码

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011872945/article/details/11771651

1、使用category对NSString 进行扩展,使可以转换为UTF-8编码与解码

首先创建一个扩展类,名字EncodingUTF8Additions,头文件代码如下:
#import <Foundation/Foundation.h>

@interface NSString (EncodingUTF8Additions)

-(NSString *) URLEncodingUTF8String;//编码
-(NSString *) URLDecodingUTF8String;//解码

@end

实现代码如下:
#import "NSString+EncodingUTF8Additions.h"

@implementation NSString (EncodingUTF8Additions)

-(NSString *)URLEncodingUTF8String{
    NSString *result = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                           (CFStringRef)self,
                                                                           NULL,
                                                                           CFSTR("!*'();:@&=+$,/?%#[]"),
                                                                           kCFStringEncodingUTF8);
    [result autorelease];
    return result;
}
-(NSString *)URLDecodingUTF8String{
    NSString *result = (NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault,
                                                                                           (CFStringRef)self,
                                                                                           CFSTR(""),
                                                                                           kCFStringEncodingUTF8);
    [result autorelease];
    return result;
}
@end
调用的时候引入"NSString+EncodingUTF8Additions.h"
调用方法如下:
NSString *text=[@"编码NSString" URLEncodingUTF8String];
    NSLog(@"编码:%@",text);
    NSLog(@"解码:%@",[text URLDecodingUTF8String]);





阅读更多

没有更多推荐了,返回首页