in method "addTarget", the first parameter "self" mean the UIControll self or the instance who call "addTartget"?

when create a instance of UIController or its subclass, we use addTarget to connect the target with a action just as belows

let btn = UIButton.init(type: .custom)
btn.frame = CGRect.init(x: 100, y: 200, width: 80, height: 44)
btn.setTitle("test", for: .normal)
btn.addTarget(self, action: #selector(self.test(sender:)), for: .touchUpInside)
self.view.addSubview(btn)


so, btn.addTarget(self,...)" what does "self" mean? By swift syntax, it seems to be the class instance who call this method. But I think it should be the button instance?


who can help me? thanks a lot.

Replies

The first parameter to addTarget is the object whose method will be called when the action fires.


It's customary for an object such as a view controller to register itself as the target, but in theory you could pass some other object there if you wanted. Perhaps you have some helper / manager object whose job it is to respond to controls. I can't really think of a case where it would be *preferred* to register some other object for an action without that object being involved though. It seems like it would be messy design. Myself I would pass the UIButton reference to the helper object, and that helper object would then register whatever actions it needed, using itself as the target for the action message that will be sent.