Escape Quotes in Objective-C

后端 未结 4 1985
Happy的楠姐
Happy的楠姐 2020-12-10 16:52

I\'m using this code snippet to encode characters to be friendly with a POST request:

   NSString *unescaped = [textField text];
   NSString *escapedString =         


        
4条回答
  •  悲&欢浪女
    2020-12-10 17:15

    First, you don't want to use __bridge_retained in your cast to a CFStringRef. Just use __bridge.

    Second, you don't have to escape the quotes manually by string replacement. Just add the quote character to the set of characters to be quoted when calling CFURLCreateStringByAddingPercentEscapes(). Like so:

    NSString *unescaped = [textField text];
    NSString *escapedString = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL,
                                                                                        (__bridge CFStringRef)unescaped,
                                                                                        NULL,
                                                                                        CFSTR("!*'();:@&=+$,/?%#[]\""),
                                                                                        kCFStringEncodingUTF8));
    

    (In addition to adding the quote to the set, I changed to use CFBridgingRelease() rather than a __bridge_transfer cast because I find it clearer. It satisfies the feeling that all CF "Create" functions need a corresponding "Release". Also, I changed the use of a @"" literal cast to CFStringRef to just a CFSTR("") literal.)

提交回复
热议问题