stringWithFormat和%不起作用

时间:2012-07-31 02:47:23

标签: iphone objective-c xcode nsstring

我有这个字符串

 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

当我使用

 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

你看到的不一样。我的问题是如何使用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%3A448%7D 

所以值(721)恰好在(448)被替换为 提前谢谢。

2 个答案:

答案 0 :(得分:3)

这是因为格式字符串中的所有%个字符都可能用于使用格式参数,就像%@一样(详见here)。

可以看到(对于一个实例)其中:

callback_params=%7B%22date

转变为:

callback_params=7                 37040ate

在这种情况下,我不确定%7B正在做什么,因为它不是一个有效的格式说明符,但%22date导致一个22个字符的十进制值,来自{{1 },后跟文字%22d

如果您希望输出字符串中有一个ate,则需要在格式字符串中使用%%

答案 1 :(得分:1)

另一种看待它的方式是,你将它作为格式字符串给出的东西实际上是数据,而不是纯粹的格式。

为了避免那些虚假的转换,你需要:

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"];
相关问题