Vlad Vlad - 23 days ago 6x
iOS Question

How to call addTarget:action:forControlEvents: from a class method?

I am trying to use a single class method to instantiate a

, based on the payload I pass in, as well as add an action handler, like this:

+ (void)instantiate: (UIButton *)button with:(NSDictionary *)payload {
[button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
button.title = payload.title;

Normally I don't have a problem if the
method was an ordinary method, but I don't know how to implement the
method in this case.

Should it be a class method? Should it be an instance method? Also If I need to make it a class method, how do I specify the
inside the


People may debate whether using a class method or an instance method is better in this case but I'll simply answer the coding question.

You can use a class method if you want. The implementation of your instantiate:with: method is fine as-is. Just add the buttonClicked: method. It needs to be class method:

+ (void)buttonClicked:(UIButton *)button {
    // do stuff