IOS使用CFURLCreateStringByAddingPercentEscapes进行URL编码

来源:互联网 发布:五月天歌词 知乎 编辑:程序博客网 时间:2024/06/14 09:45

iOS程序访问HTTP资源时需要对URL进行UTF8编码,我在之前一直都喜欢使用NSString的stringByAddingPercentEscapesUsingEncoding方法进行编码。今天在使用Analyze分析工程时,提示下面的方法可能存在内存泄露:
NSString *enString =(NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)stringURL, NULL, NULL, kCFStringEncodingUTF8);
注意到这个方法也是一个编码方案,就查询了两种方式的区别,有些收获。额外学习UITabBarController隐藏tabBar以及addChildViewController
stringByAddingPercentEscapesUsingEncoding方法有一个问题:不会转转URL中的”%&?”等符号[这个很好理解,因为不好区分这些特殊字符到底是连接符号还是参数值]。这些字符在URL语法中有特殊的含义,如果在URL的参数中有这些字符,就需要转化为”%+ASCII”的形式。如果参数中存在这些字符,而我们又使用了stringByAddingPercentEscapesUsingEncoding方法,则服务器会将参数中的没有转义的&当做分隔符,造成分析错误。因为我的工程中几乎没有在参数中存在%&等符号的情况,所以一直用也没问题。但咱们还是要使用正规的方式。
一般来说都是用:

CFStringRef CFURLCreateStringByAddingPercentEscapes(  CFAllocatorRef allocator,  CFStringRef originalString, /*待转码的类型*/  CFStringRef charactersToLeaveUnescaped, /*指示不转义的字符*/  CFStringRef legalURLCharactersToBeEscaped,/*指示确定转义的字符*/  CFStringEncoding encoding); /*编码类型*/  

1 2 3 4 5 6CFStringRef CFURLCreateStringByAddingPercentEscapes( CFAllocatorRef allocator, CFStringRef originalString, /*待转码的类型*/ CFStringRef charactersToLeaveUnescaped, /*指示不转义的字符*/ CFStringRef legalURLCharactersToBeEscaped,/*指示确定转义的字符*/ CFStringEncoding encoding); /*编码类型*/ 

方案就是单独编码参数值(如果编码整个URL的话会讲URL分割符&等也编码),最后拼接成完整的字符串。
示例Demo如下:

CFStringRef escaped = CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)self, NULL, (CFStringRef)@"!*'();:@&=+$,/?%#[]",kCFStringEncodingUTF8);  NSString *out = [NSString stringWithString:(NSString *)escaped];  CFRelease(escaped);//记得释放 

1 2 3CFStringRef escaped = CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)self, NULL, (CFStringRef)@"!*'();:@&=+$,/?%#[]",kCFStringEncodingUTF8); NSString *out = [NSString stringWithString:(NSString *)escaped]; CFRelease(escaped);//记得释放

另外一个小知识点:
在之前做图片切割时经常用到如下代码

CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, rect);  UIImage *newImage = [UIImage imageWithCGImage:newImageRef];  


1 2CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, rect); UIImage *newImage = [UIImage imageWithCGImage:newImageRef]; 

实际上这个代码会造成内存泄露,正确的方式是还需要释放newImageRef,如下:

CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, rect);  UIImage *newImage = [UIImage imageWithCGImage:newImageRef];  CGImageRelease(newImageRef);  

1 2 3CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, rect); UIImage *newImage = [UIImage imageWithCGImage:newImageRef]; CGImageRelease(newImageRef);
0 0
原创粉丝点击