Problem casting an int as a NSString
I am working on an iPhone 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?
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:
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.