adellam
adellam

Reputation: 831

stringWithFormat and % not working

i have this string

 NSString *jsonString = @"http://www.soccerway.com/a/block_home_matches?block_id=block_home_matches_14&callback_params=%7B%22date%22%3A%222012-07-31%22%2C%22display%22%3A%22all%22%7D&action=showMatches&params=%7B%22competition_id%22%3A721%7D";
 NSLog(@"%@",jsonString);

the output is 

http://www.soccerway.com/a/block_home_matches?block_id=block_home_matches_14&callback_params=%7B%22date%22%3A%222012-07-31%22%2C%22display%22%3A%22all%22%7D&action=showMatches&params=%7B%22competition_id%22%3A721%7D

when i use

 NSString *linkId = @"448";//not a constant value only for example 
 NSString *jsonString = [NSString stringWithFormat:@"http://www.soccerway.com/a/block_home_matches?block_id=block_home_matches_14&callback_params=%7B%22date%22%3A%222012-07-31%22%2C%22display%22%3A%22all%22%7D&action=showMatches&params=%7B%22competition_id%22%3A%@%7D",linkId];

 the output is 

http://www.soccerway.com/a/block_home_matches?block_id=block_home_matches_14&callback_params=7                 37040ate23A222㿠                 37040isplay23A0x1.21800000507cp-1027ll27D&action=showMatches&params=7                     –ompetition_id23A(null)      0

as you see not the same.My question is how to use stringWithFormat to get this result:

  http://www.soccerway.com/a/block_home_matches?block_id=block_home_matches_14&callback_params=%7B%22date%22%3A%222012-07-31%22%2C%22display%22%3A%22all%22%7D&action=showMatches&params=%7B%22competition_id%22%3A448%7D 

so the value (721) just at the and is replaced by (448) thanks in advance.

Upvotes: 0

Views: 499

Answers (2)

paxdiablo
paxdiablo

Reputation: 881423

It's because all those % characters inside your format string are being potentially used to used the format arguments, much like %@ (see here for details).

This can be seen (for one instance) where:

callback_params=%7B%22date

is transformed into:

callback_params=7                 37040ate

In that case, I'm not sure what the %7B is doing since it's not a valid format specifier, but the %22date is resulting in a 22-character decimal value, from %22d, followed by the literal ate.

You need to use %% in your format string if you want a single % in the output string.

Upvotes: 3

Phillip Mills
Phillip Mills

Reputation: 31016

The other way of looking at it is that the thing you're giving it as a format string is really data, not purely a format.

To be safe from those spurious conversions, you'd want:

NSString *jsonString = [NSString stringWithFormat:@"%@%@%@", @"http://www.soccerway.com/a/block_home_matches?block_id=block_home_matches_14&callback_params=%7B%22date%22%3A%222012-07-31%22%2C%22display%22%3A%22all%22%7D&action=showMatches&params=%7B%22competition_id%22%3A",linkId, @"%7D"];

Upvotes: 1

Related Questions