4

Possible Duplicate:
How to fire uibarbuttonitem click event programmatically

I have created an uibarbuttonitem dynamically and it works properly. I want to fire that uibarbutton item action(click) programatically for unit testing.

Even though the code work properly when I log the action of the bar button item in the application code (not on testing code) it gives null. The code I have used is given below.

NSLog(@"%@",NSStringFromSelector(barButton.action)); 

In the testing code I have created a bar button called logout and assign barbutton to that.To click the bar button item programatically I followed the following code.

[logout.target performSelector:logout.action];

But it didn't work . I logged the action of logout button and it also gives null.

NSLog(@"%@",logout.action);

I want to know how to programatically click a uibarbuttonitem which created dynamically .

Community
  • 1
  • 1
Aruna Herath
  • 6,241
  • 1
  • 40
  • 59

1 Answers1

8

This code worked with me

//in viewDidLoad
item = [[UIBarButtonItem alloc] initWithTitle:@"test" style:UIBarButtonItemStyleDone target:self action:@selector(logout)];    
toolBar.items = [NSArray arrayWithObject:item];

//In viewWillAppear
[item.target performSelector:item.action];

- (void) logout
{
    NSLog(@"Called");
}

I dont know what you mean by click, but the above works

Omar Abdelhafith
  • 21,163
  • 5
  • 52
  • 56
  • i am doing this for unit testing. i am writing unit testing for someone else's code. so i cant change it. when i log the action of the button it gives null. so performselector doesnt work. when i ran the application (the one i am testing) it works fine. please be kind enough to give this some thought. – Aruna Herath Jun 28 '12 at 09:41
  • what does it give you null, did you try the code i posted above? – Omar Abdelhafith Jun 28 '12 at 09:42
  • yes i did. the action of the button is null. so a selector is not set properly for the button? unfortunately i cant find out in the code(the one i am testing) where it is set. – Aruna Herath Jun 28 '12 at 09:43
  • then maybe it is not set, or even its set later after you do your unit test – Omar Abdelhafith Jun 28 '12 at 09:46
  • is this the only way to make a uibarbuttonitem do what it does. (setting a selector as its action)? could the selector be null and button still does what it does? – Aruna Herath Jun 28 '12 at 09:52
  • Nope it should have an action – Omar Abdelhafith Jun 28 '12 at 09:54