Escape Quotes in Objective-C

十年热恋 提交于 2019-11-28 11:15:06

I think I didn't word the question correctly.

I needed to take the user inputted NSString from [textField text] and make sure that if there are quotation marks in the string, they are escaped properly in order to send through a POST statement.

My solution was:

unescaped = [unescaped stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];

Thanks

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.)

Quotes are to be escaped with \".

As in:

(CFStringRef)@"I'm an \"example\""
adi27

try using \" instead of using " directly...

Special Characters like Quotes, slashes and others require \ to make that character to remove its special functionality.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!