BloonsTowerDefence
BloonsTowerDefence

Reputation: 1204

Declaring a string at run time with variables

I am trying to create a string with parameters that I pass to a web service, but I never know how many parameters there are going to be until runtime.

All of the parameters are stored in an array, and I iterate through the array, adding each one the the string.

The variables on the .php side are labeled field1, field2, field3, etc.

My problem lies when I try to declare the string in the for loop. I am trying to use x and append that to the word "field" so that I can end up with field1, field2, filed3, etc.

When I try to do this, there is an error message saying that there were more parameters than expected.

Here's what I have:

NSString *URLWithParameters = [NSString stringWithFormat:@"http://www.mywebsite/service?"];

for (int x = 0; x < [fields count]; x++) {

    NSString *temp = [NSString stringWithString:@"field%i=%@&", x, (NSString *)[fields objectAtIndex:x]];

    URLWithParameters = [URLWithParameters stringByAppendingString:temp];

}

Upvotes: 0

Views: 108

Answers (2)

Justin Boo
Justin Boo

Reputation: 10198

Change:

NSString *temp = [NSString stringWithString:@"field%i=%@&", x, (NSString *)[fields objectAtIndex:x]];

to:

NSString *temp = [NSString stringWithFormat:@"field%i=%@&", x, (NSString *)[fields objectAtIndex:x]];


Note:

Why You use [NSString stringWithFormat:@"http://www.mywebsite/service?"] when You can use it directly like this:

NSString *URLWithParameters = @"http://www.mywebsite/service?";

or using stringWithformat:

NSString *URLWithParameters = [NSString stringWithFormat:@"%@", @"http://www.mywebsite/service?"];

Upvotes: 1

Joshua Weinberg
Joshua Weinberg

Reputation: 28688

stringWithString should be stringWithFormat.

Upvotes: 2

Related Questions