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

那年仲夏 提交于 2019-11-27 08:48:42

问题


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]];


来源:https://stackoverflow.com/questions/11321396/why-do-i-get-this-error-when-i-try-to-pass-a-parameter-in-nsurl-in-ios-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!