Search code examples
objective-ciosnsurlconnectionnsurl

Why do I get this error when I try to pass a parameter in NSURL in iOS app?


This is what I have in a public method - (IBAction)methodName

NSString *quoteNumber = [[self textBox] text];

NSURL *url = [[NSURL alloc] initWithString:@"http://TestSite.com/virdirectory/Webservice1/Service1.asmx/GetQuote?number=%d", quoteNumber];

The error I get is:

Too many arguments to method call, expected 1, have 2

What am I doing wrong?


Solution

  • The initWithString method can only accept a normal NSString, you are passing it a formatted NSString, Take a look at this code:

        NSURL *url = [[NSURL alloc] initWithString:[NSString stringWithFormat:@"http://TestSite.com/virdirectory/Webservice1/Service1.asmx/GetQuote?number=%d", quotedNumber]];
    

    That might be a bit confusing, you can break it up as follows:

    NSString *urlString = [NSString stringWithFormat:@"http://TestSite.com/virdirectory/Webservice1/Service1.asmx/GetQuote?number=%d", quotedNumber];
    
    NSURL *url = [[NSURL alloc] initWithString:urlString];
    

    Now your string is properly formated, and the NSURL initWithString method will work!

    Also, just so it is clearer for you in the future, you can take advantage of Objective-C's dot notation syntax when you set your quoteNumber string, as follows:

    NSString *quoteNumber = self.textBox.text;
    

    Also, you are trying to pass this quoted number into your urlString as a digit (as seen with the %d), remember that quotedNumber is a NSString object, and will crash when you try to pass it to the stringWithFormat method. You must convert the string first to a NSInteger, or NSUInteger.

    Please refer to this SO question to how to do that (don't worry it's very easy)!