简体   繁体   中英

What’s the difference between action methods and protocol methods?

I started learning iOS programming, and I came across something like this: to handle the event when users press return after input text in a UITextField, my view controller implements "textFieldShouldReturn: textField" from UITexTFieldDelegate protocol. But, to handle the event when "Editing Did End", I need to declare an IBAction method in the view controller, and wire up the event to it.

What is the difference between these two types of event handling methods?

The "Editing Did End" is part of the UIControl class, and UITextField inherits it from UIControl. This kind of event is one of the registered touch events this class responds to and the way to do this registration is to assign an action (IBAction using IB) to the particular event.

The delegate protocol part of the implementation is due to the "extension mechanism" provided by delegate protocols in Cocoa design patterns. Essentially the idea is that you can provide special behavior to the object, in this case UITextField, without subclassing. Imagine for example you want some kind of validation before allowing the "return" button. In such case you would be forced to setup a UITextField subclass with this validation code hard-coded in it. And for each different validation code you would be forced to implement a different subclass. Using the delegate mechanism, you delegates something else (typically the text field owner view controller) to perform this "class extension", without subclassing. So you do class customization per-instance.

Note that this approach is coherent: everything that is considered as "event" (touch up, touch down, did end editing, all related to some user interaction with the display and not with the keyboard) is wired to the class using the UIControl target-action mechanism. Everything that is "specific" of the instance (and not the class!) is managed using the delegate.

In protocols (denoted with @protocol //name\\ superclass) one can specify methods that the conforming class either can, will, or must take on with @optional, or @required methods. One might use protocols to say, pass data from one view to the next, so long as the second view conformed to the protocol (like @implementation Classname: NSObject ) This is in stark contrast to IBActions and void functions which are local and impassable to other controllers (except with class methods).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM