简体   繁体   中英

How do I add a number to an NSURL? Too many arguments error

I've got a small problem that seems a little bit odd to me. I often used NSString or NSLog while adding NSNumbers into several places:

NSNumber *categoryId = [[NSNumber alloc]initWithInt:0];
NSURL *url = [NSURL URLWithString:@"http://shop.rs/api/json.php?action=getCategoryByCategory&category=%i",[categoryId integerValue]];

Now xcode tells me that I'm too many arguments. What am I doing wrong? Setting up an NSNumber into NSStrings or NSLogs works as I did it above.

Best Regards

What is wrong is on

NSURL *url = [NSURL URLWithString:@"http://shop.rs/api/json.php?action=getCategoryByCategory&category=%i",[categoryId integerValue]];

you are calling URLWithString: and then pass in a string that is not being formatted correctly. If you want to do it all on one line then you need to be using stringWithFormat: like

NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://shop.rs/api/json.php?action=getCategoryByCategory&category=%i",[categoryId integerValue]]];

Because it is adding a parameter you can't just create a string like you normally would with @"some text" you need to format it using the stringWithFormat: which will return an NSString * with the text held within @"" and the paramters you pass in. So [NSString stringWithFormat:@"My String will come with %@", @"Apples"]; this would provide an NSString with "My String will come with Apples" . For more information check out the Apple Documentation for NSString and stringWithFormat:

Try this :

NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://shop.rs/api/json.phpaction=getCategoryByCategory&category=%i", [categoryId integerValue]]];

Initially code was wrong because of : "categoryId integerValue]" (I forgot a '[').

You can use NSString to form your NSURL . You can then pass it to your URLWithString like below:

NSNumber *categoryId = [NSNumber numberWithInteger:0]; 
NSString *urlString = [NSString stringWithFormat:@"http://shop.rs/api/json.php?action=getCategoryByCategory&category=%i",[categoryId integerValue]];
NSURL *url = [NSURL URLWithString:urlString];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM