Why do I get this error when I try to pass a param

2019-01-20 20:08发布

问题:

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?

回答1:

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)!



回答2:

I think you are thinking of NSString's stringWithFormat::

[NSURL URLWithString:[NSString stringWithFormat:@"http://TestSite.com/virdirectory/Webservice1/Service1.asmx/GetQuote?number=%@", quoteNumber]]

Also note the change to %@ for the format specifier, since it is an instance of NSString (not an int)



回答3:

You need to format your string. Try this:

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


回答4:

The problem is

[NSURL initWithString:]

requires ONE parameter of NSString type but you passed TWO parameters .

You need to pass a single NSString parameter . Change your code from

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

to

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