1

I know the %% method, but it's not working :(.

with NSLog

 NSLog(@"%%5B hello %%5D");

prints

%5B hello %5D

but with NSString

NSString *str = [NSString stringWithFormat:@"%%5B %@ %%5D",@"hello"];
NSLog(str);

prints

5 hello 68233204

Why?

Daniel
  • 181
  • 1
  • 10

2 Answers2

3

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");
Lily Ballard
  • 182,031
  • 33
  • 381
  • 347
  • 2
    note: calls through NSLog (`NSLog(str);`) should always use a format specification: `NSLog(@"%@",str);` – justin Apr 26 '11 at 17:48
1

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.

Community
  • 1
  • 1
Chris Wagner
  • 20,773
  • 8
  • 74
  • 95