Darren
Darren

Reputation: 10129

How to get the target of a UIBarButtonItem

I have the following code in a UIViewController subclass:

MyViewController *viewController = [[MyViewController alloc] init];
viewController.title = title;

UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"image"]
                                                               style:UIBarButtonItemStyleDone
                                                              target:self 
                                                              action:@selector(mySelector)]; 
viewController.navigationItem.leftBarButtonItem = doneButton;


 NSLog(@"Class name:%@",[viewController.navigationItem.leftBarButtonItem.target className]);

The code crashes on the NSLog statement and there is a warning saying no className method found. Isn't the target property an object, and therefore I should be able to call className on it?

What I'm actually trying to do eventually is call mySelector from the viewController without pressing the button. Is there a good way to do this?

Upvotes: 1

Views: 1258

Answers (2)

Jess Bowers
Jess Bowers

Reputation: 2973

To perform the selector directly, try calling performSelector:

    [[doneButton target] performSelector:[doneButton action]];

Upvotes: 3

Mathieu Hausherr
Mathieu Hausherr

Reputation: 3485

The correct method is class instead of className.

If your trying to simulate a touch on the button why not just write:

[self mySelector];

Upvotes: 3

Related Questions