1

Right now I am using the delegate, but I suspect it's bad form.

I programatically create an identical UIBarButtonItem in numerous, different view controllers.

My button's target is myAppDelegate, and its action is defined therein.

What is a better way of doing this? Or am I just supposed to copy and paste the identical action into no-matter-how-many view controllers that instantiate the identical bar button?

Okay, now suppose the action is identical in all respects but one: It varies only in that it should send a presentViewController message to the view controller that instantiated the button that sent the action. Thus, in the action, I can send a presentViewController message to sender, which is an instance of the button, but I know no means of reaching the view controller that instantiated that instance of the button.

mkc842
  • 2,361
  • 2
  • 26
  • 38
  • What exactly is the button doing? Making each button talk to the app delegate is very likely to be the wrong thing to do, but to figure out what the right thing is, I think it would be helpful if you were a bit more specific. – jscs May 15 '13 at 05:49
  • Okay, I guess that's answered in [your previous question](http://stackoverflow.com/questions/16556761/how-does-forwardingtargetforselector-work). – jscs May 15 '13 at 05:49
  • yeah, i just updated it here, too. – mkc842 May 15 '13 at 05:51

2 Answers2

1

Each view controller simply needs to set itself as the target of the button when the button is created. The button's action selector will then be sent to the correct controller.

As for the selector itself, create a category on UIViewController to contain the button's action:

@implemenation UIViewController (MKCBarButtonItemAction)

- (void)MKCDoThatThingIDo
{
    // Do things.

    [self presentViewController:[self theOtherViewControllerWhatINeedToDisplay]
                       animated:YES
                     completion:^{
                        // Do more things.
                    }];

    // Do yet other things.

}

@end
jscs
  • 63,694
  • 13
  • 151
  • 195
0

If you've common methods for multiple view controllers defined in AppDelegate file, then you can make call to those actions using delegate object something like,

#define appDelegateObj (AppDelegate *)[UIApplication sharedApplication].delegate;

Where, AppDelegate is your delegate file class name, also define this macro at global so you can access it from anywhere,

Now where ever you want to call any function, just use like [appDelegateObj functionName];

Here's one thing, if you can make class methods into delegate file then, it can used with using class name, like [AppDelegate functionName]; 

class methods defined like +(void)functionName{...} and it can't access to class instance variables and methods.

Hemang
  • 26,840
  • 19
  • 119
  • 186