Search code examples
iosobjective-cnsurl

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


Solution

  • 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: