jroyce
jroyce

Reputation: 2148

How do I call a button method from ViewController?

I have a method addClicked that gets called when a button on the navigation bar is clicked. I want to call this later on in the code without having to click the button. What is the syntax for calling this method?

    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] 
                                             initWithBarButtonSystemItem:UIBarButtonSystemItemAdd 
                                             target:self action:@selector(add_Clicked:)];

The function is calls looks like this:

- (void) add_Clicked:(id)sender {

I tried:

[self add_Clicked:];

[add_Clicked:];

[self add_Clicked: self];

The last works but I'm not sure why. Can someone provide a link to the doc the would explain how this works?

Upvotes: 1

Views: 129

Answers (3)

nycynik
nycynik

Reputation: 7541

Another alternative to the suggestions, depending on what your doing, is to add another method to the class and have the method called form the callback to call it.

- (void) add_Clicked:(id)sender {
  [self goAddSomething];
}


- (void) goAddSomething {
  /* add the code here to handle add. */
}

Then in another part of your code, you could call [self goAddSomething]; and not have to use nil.

Upvotes: 1

tams
tams

Reputation: 830

The last one works because you added the current class as the target "target:self", but the target is (id) so the sender could be any object in theory.

Upvotes: 1

Darren
Darren

Reputation: 10398

You have to pass something for the sender. That's why the last one works.

Try [self add_Clicked:nil]

Upvotes: 1

Related Questions