iosobjective-cuibuttondelegatesaddtarget

Delegate method or Global declaration to add action for UIButton?


In my custom view I’ve created one button. To add action for that button which is feasible solution Creating Delegate method or Declaring UIButton as global variable and addTaget. Suggest me please.


Solution

  • I'd highly recommend not using global vars as much as possible. Global data (constants) are good, but global variables are high maintenance since anyone can modify it.

    There are 2 cases why you may want a global variable:

    1. It has to trigger different actions in multiple unrelated submodules. What I'd recommend here is to create the button and target in a class/function, and send a notification in the target. Make the different subsystems register to the notification and take appropriate action
    2. You just have one class to take an action item, but it's convenient to not have delegates and use global vars. I request you to prefer design to convenience.