Objective-C basic notes (5) Protocol, objectivec Programming

Source: Internet
Author: User

Objective-C basic notes (5) Protocol, objectivec Programming

Protocol is simply a list of methods. The declared methods can be implemented by any class. This mode is generally called the delegation mode.

In IOS and OS X development, Apple uses a large number of proxy modes to decouple View (UI control) and Controller (Controller) in MVC.

Next, let's take a look at the familiar Android button listening process, and then compare and understand the delegation.

First, I create a simple Android project and place a button in Layout, as shown below:

<LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android" android: layout_width = "fill_parent" android: layout_height = "fill_parent" android: orientation = "vertical"> <Button android: id = "@ + id/mybutton" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: text = "button"/> </LinearLayout>
Package com. example. helloword; import android. app. activity; import android. OS. bundle; import android. view. view; import android. view. view. onClickListener; import android. view. view. onLongClickListener; import android. widget. button; import android. widget. toast; public class MainActivity extends Activity {@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); Button button = (Button) findViewById (R. id. mybutton); button. setOnClickListener (new MyOnClickListener ();} class MyOnClickListener implements OnClickListener {@ Overridepublic void onClick (View arg0) {Toast. makeText (MainActivity. this, "click", Toast. LENGTH_SHORT ). show () ;}} class MyonLongClickListener implements OnLongClickListener {@ Overridepublic boolean onLongClick (View arg0) {Toast. makeText (MainActivity. this, "Long-pressed button", Toast. LENGTH_SHORT ). show (); return false ;}}}
OnClickListener is an internal class of View and an interface defined by View. The source code of OnClickListener is as follows:

    /**     * Interface definition for a callback to be invoked when a view is clicked.     */    public interface OnClickListener {        /**         * Called when a view has been clicked.         *         * @param v The view that was clicked.         */        void onClick(View v);    }
Let's take a look at the setOnClickListener method.

    public void setOnClickListener(OnClickListener l) {        if (!isClickable()) {            setClickable(true);        }        getListenerInfo().mOnClickListener = l;    }
First, judge whether the View is clickable. Let's take a look at the following sentence: getListenerInfo (). mOnClickListener = 1;

    ListenerInfo getListenerInfo() {        if (mListenerInfo != null) {            return mListenerInfo;        }        mListenerInfo = new ListenerInfo();        return mListenerInfo;    }
From this code, we can see that our OnClickListener instance is saved to the ListenerInfor object. Why is the ListenerInfor object used? Since I do not have the Android system source code, I will not keep tracking. I can guess this class holds our OnClickeListener object. When the system responds to the screen click event, it will distribute it through the event, you can call the onClick method to notify all objects that implement the OnClickeListener interface.

Next we will simulate the implementation of Button listening in IOS.


Button. h file

# Import <Foundation/Foundation. h> @ class Button; // <> indicates implementing a protocol. // here it is equivalent to OnClickListener @ protocol ButtonDelegate <NSObject> // passing the Button object to the listener, to determine the specific call instance-(void) onClick :( Button *) btn; @ end @ protocol ButtonLongClickDelegate <NSObject>-(void) onLongClick :( Button *) btn; @ end @ interface Button: NSObject // delegate is the listener of the Button. // id represents any OC object @ property (nonatomic, retain) id <ButtonDelegate> delegate; @ property (nonatomic, retain) id <ButtonLongClickDelegate> longClickDeleate; // simulate the system call the click method-(void) click; // simulate the system call the longclick method-(void) longClick; @ end
Button. m file

# Import "Button. h "@ implementation Button-(void) click {// when the Button is clicked, the listener should be notified (simulated here) // If The onClick method is implemented, call The onClick method if ([_ delegate respondsToSelector: @ selector (onClick :)]) {[_ delegate onClick: self];} else {NSLog (@ "onClick listener not implemented") ;}}-(void) longClick {// The button is long pressed (Simulated System) if ([_ delegate respondsToSelector: @ selector (onClick :)]) {[_ longClickDeleate onLongClick: self];} else {NSLog (@ "longClick listener not implemented");}-(void) dealloc {[_ delegate release]; [_ longClickDeleate release]; [super dealloc];} @ end
ButtonListener. h

# Import <Foundation/Foundation. h> @ protocol ButtonDelegate; // click the implementation button and click the protocol @ interface ButtonListener: NSObject <ButtonDelegate> @ end
ButtonListener. m

# Import "ButtonListener. h "# import" Button. h "@ implementation ButtonListener-(void) onClick :( Button *) btn {NSLog (@" the Button is clicked ");} @ end
ButtonLongClickListener. h file

# Import <Foundation/Foundation. h> // declare the protocol in advance. The same as @ class, @ protocol ButtonLongClickDelegate; @ interface ButtonLongClickListener: NSObject <ButtonLongClickDelegate> @ end
ButtonLongClickListener. m file

# Import "ButtonLongClickListener. h "# import" Button. h "@ implementation ButtonLongClickListener-(void) onLongClick :( Button *) btn {NSLog (@" the Button is long pressed ");} @ end
Main. m file

# Import <Foundation/Foundation. h> # import "Button. h "# import" ButtonListener. h "# import" ButtonLongClickListener. h "int main (int argc, const char * argv []) {@ autoreleasepool {// initialize a Button button * Button = [[[Button alloc] init] autorelease]; // initialize the button listener ButtonListener * listener = [[[ButtonListener alloc] init] autorelener]; // initialize a button long-pressing listener ButtonLongClickListener * longClickListener = [[[ButtonLongClickListener alloc] init] autorelease]; // set the button listener button. delegate = listener; // set the listener button of the long-pressed button. longClickDeleate = longClickListener; // click the button [button click]; // long-pressed button [button longClick];} return 0 ;}
Output result:

13:52:35. 215 ProtocalTest [845: 82273] button clicked

13:52:35. 216 ProtocalTest [845: 82273] button was long pressed


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.