2

My senior was reviewing my code and he found that I have used UIButton addTarget method like this

override func viewDidLoad() {
    super.viewDidLoad()
    self.btnAccount.addTarget(self, action: #selector(Accounts(_:)), for: .touchUpInside) 
  }

Now he is saying that you should not use addTarget in viewDidLoad it will take time(kind of memory management thing I didn't get it) to load view controller but I didn't find it relevant that's why I am asking this question did I made some mistake by doing this should I always make actions

Devil Decoder
  • 966
  • 1
  • 10
  • 26

1 Answers1

8

I didn't hear of that and even if it is true, you should never try to do premature optimization on your app. UIButton is a UIControl object, which follows an event-listener pattern, which is often implemented with a hashmap (NSDictionary in Objective-C) of targets ('aka' Listeners or Observers) and it is not very time-consuming operation.


I personally prefer to setup all UI component right at the beginning:

lazy var btnAccount: UIButton = {
    let btn = UIButton

    // setup button's appearance

    btn.addTarget(self, action: #selector(Accounts(_:)), for: .touchUpInside)
    return btn
}()

P.S. Please ask him about the source of the fact and let me know.

Mojtaba Hosseini
  • 95,414
  • 31
  • 268
  • 278