Too many arguments to method call

2019-08-05 14:28发布

问题:

I am trying to set the initial text for what the twitter message should say in my app using a NSString from my appDelegate. Check out the code here:

    NSString *tweet;
tweet=[MyWebFunction tweet:appDelegate.stadium_id];


if([deviceType hasPrefix:@"5."]){

    // Create the view controller
    TWTweetComposeViewController *twitter = [[TWTweetComposeViewController alloc] init];

    [twitter setInitialText:@"@%",tweet];

The problem is, is there is an error at the twitter setInitialText that there are Too many arguments to method call, expected 1, have 2. ?!?!?

Any help is greatly appreciated. :)

回答1:

The TWTweetComposeViewController method setInitialText only takes one argument, being of type NSString*. You cannot simply format any and all NSString variables passed to a method as you can with the NSString method stringWithFormat (which is, I imagine, where you've seen the syntax [NSString stringWithFormat:@"%@", myString]).

In your case, you either need to simply call:

[twitter setInitialText:tweet];

or call:

[twitter setInitialText:[NSString stringWithFormat:@"%@", tweet]]

EDIT
I feel it necessary to add, to further your understanding, that a method only takes a variable number of arguments (such as stringWithFormat) when its declaration ends with ...

For example, looking in the docs for NSString reveals that stringWithFormat is declared as such:

+(id) stringWithFormat:(NSString *)format, ...;

Similarly, arrayWithObjects in NSArray is declared as such:

+(id) arrayWithObjects:(id)firstObj, ...;

which one would use like:

NSString* myString1 = @"foo";
NSString* myString2 = @"bar";
NSNumber* myNumber = [NSNumber numberWithInt:42];
NSArray* myArray = [NSArray arrayWithObjects:myString1, myString2, myNumber, nil];


回答2:

Try [twitter setInitialText:tweet];

If you really need formatted text for a more complex case, try

[twitter setInitialText:[NSString stringWithFormat:@"%@", tweet]];



回答3:

"[twitter setInitialText:@"@%",tweet];"

you just got your "@" and your "%" the wrong way round it should be

[twitter setInitialText:@"**%@**",tweet];