I know the %% method, but it's not working :(.
with NSLog
NSLog(@"%%5B hello %%5D");
prints
%5B hello %5D
but开发者_C百科 with NSString
NSString *str = [NSString stringWithFormat:@"%%5B %@ %%5D",@"hello"]; NSLog(str);
prints
5 hello 68233204
Why?
It's because you left out a line of code. In your stringWithFormat:
version you probably have something like
NSString *str = [NSString stringWithFormat:@"%%5B5%%5D"];
NSLog(str);
The problem is you've now doubly-interpreted format characters in the string. Remember, the first arg to NSLog()
and to +[NSString stringWithFormat:]
is a format string, where %
characters are treated specially. In both cases, you can easily preserve the original version of the string (and strip out the duplicate %'s ahead of time) by using actual format strings, as in
NSLog(@"%@", @"%5B%5D");
You do need to use stringWithFormat:
if you aren't going to pass in any arguments, you should be able to just use
NSString *str = @"%%5B%%5D";
But as to "why", what you are experiencing is occurring, I am not sure... Try passing in an argument and see if it still happens. Maybe there is a bug when no arguments are passed?
According to this post you are escaping it correctly.
String format specifiers document says you are doing it right too.
精彩评论