开发者

Problem casting an int as a NSString

I am working on an iPhon开发者_如何学Goe app that is using some urls and I am running into difficulty appending ints onto the end of them. I have the following line of code

        NSURL *urlCards = [[NSURL alloc] initWithString:(@"http://website.edu/get_stuff/%@",[NSString stringWithFormat:@"%d",_stuffID])];

that I need to simply be appending an int to the end of. When I print out the results of the NSURL urlCards, I simply get the value of the int that I am passing in, or the value of _deckID.

I have verified that the _deckID which is declared merely as a local int does indeed have the correct value at run time.

What am I missing?

Thanks!!


What you've encountered is the comma operator. The comma operator evaluates each of its operands for their side effects, and evaluates to the result of the last expression. For example:

int i;
int j;
int z;

z = (i = 4, j = 3, i + j);
// z is now 7

What you've got here:

(@"http://website.edu/get_stuff/%@",[NSString stringWithFormat:@"%d",_stuffID])

Evaluates to just

[NSString stringWithFormat:@"%d", _stuffID]

This is because the first part @"..." is an expression that has no side effects, and the result of the comma operator is the result of the [NSString stringWithFormat:] method.

What you are looking for I think, it this:

NSString *urlString = [NSString stringWithFormat:@"http://website.edu/get_stuff/%d",_stuffID];
NSURL *urlCards = [[NSURL alloc] initWithString:urlString];

You can also do it in one line, like KingofBliss's answer.


NSString *urlString=[NSString stringWithFormat:@"http://website.edu/get_stuff/%d",_stuffID];
NSURL *urlCards = [[NSURL alloc] initWithString:urlString];

use this it solves your problem.


Why can't you try like this:

NSURL *urlCards = [[NSURL alloc] initWithString:[NSString stringWithFormat:@"http://website.edu/get_stuff/%d",_stuffID]];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜