Objective-C learning path delegation Mode

Source: Internet
Author: User
Objective-C learning path delegation Mode


    Objective-CLearning pathDelegateThe mode is described in this article,DelegateMode is very important, such as the official interactive API,DelegateThis mode is very common, for example, setanimationdelegate of uiview, set the animationDelegate. Not understoodDelegateMode, you cannot quickly understand the use of many APIs, because they use the same mode. If you understand this mode, you will get started immediately.

    Let's talk about what the delegated mode is for in plain words. ActuallyObjective-CThe delegate mode in is similar to the callback mechanism or listener mechanism in Java. Or, it is similar to the onclick events and functions in JavaScript. For example, if you want to do something after clicking a button, there must be a View class and a control class, no matter what language or development tool you are using. The View class knows when a user clicks the button, but does not know what to do after clicking it. The control class knows what to do after clicking the button, rather than when the user clicks. Then, you can delegate the control class to the View class. When you click, The View class calls the control class.

    If you have used Java swing for local graphical interface development, you should know that the view class contains a large number of (anonymous) Internal classes, or you want to register the listener, these mechanisms play a similar role as objective-C delegate. It can be understood as follows: Listeners and (anonymous) Internal classes are the part of implementation, but they do not know when something will happen. view classes call listeners when an event is sent, (anonymous) internal class, View class knows when something happens.

    Write a simple example in the main method to simulate the role of delegation in view and control. Here, I have a screen class. Let's take it as a view. The requirement is that an explosion occurs when a screen is clicked. Then I have an action class which will implement the explosion action.

    Delegate mode using protocols

    The code below is very blunt, and will gradually evolve into a reasonable implementation. The first example is to explain how to implement it technically without practical application.

    Here, because it is a simulation, we can regard the main method as a user re-operate interface, create a view by clicking it, and then call the screen instance method ontouch, here, the user clicks the screen by hand:

     
     
    1. #import <Foundation/Foundation.h>   
    2. #import "Screen.h"  
    3. int main (int argc, const char * argv[]) {   
    4.     NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];  
    5.     Screen *screen=[[Screen alloc] init];   
    6.     screenscreen.delegate=screen;   
    7.     [screen onTouch];   
    8.     [screen release];   
    9.     [pool drain];   
    10.     return 0;   

    Skip the following steps:

     
     
    1. screenscreen.delegate=screen; 

    Later.

    Action class, which is implemented using the protocol here:

     
     
    1. #import <Cocoa/Cocoa.h> 
    2. @protocol Action <NSObject> 
    3. - (void) doAction;  
    4. @end 

    Is a protocol that inherits the nsobject protocol. Note that nsobject is not a class here, and there is indeed a class with the same name. This Protocol defines a doaction method, which can meet the needs of "screen explosion" for example.

    Next we will talk about the screen class and header files:

     
     
    1. #import <Foundation/Foundation.h>   
    2. #import "Action.h"  
    3. @interface Screen : NSObject <Action> {   
    4.     id <Action> delegate;   
    5. }  
    6. @property(nonatomic,retain) id <Action> delegate;  
    7. - (void) onTouch;  
    8. @end 

    The ontouch method is used to simulate the method called after the screen is clicked by the user. The screen class implements the Action protocol. It also has an action-type member delegate. In order to set the delegate instance variable, property is also set for it.

    Let's take a look at the implementation file:

     
     
    1. #import "Screen.h"  
    2. @implementation Screen  
    3. @synthesize delegate;  
    4. - (void) onTouch{   
    5.     NSLog(@"on touch …");   
    6.     if ([delegate conformsToProtocol:@protocol(Action)] &&   
    7.         [delegate respondsToSelector:@selector(doAction)]) {   
    8.         [delegate performSelector:@selector(doAction)];   
    9.     }   
    10.     NSLog(@"on touched.");   
    11. }  
    12. - (void) doAction{   
    13.     NSLog(@"Bang!!!!!!!!!");   
    14. }  
    15. @end 

    Here we will focus on the internal code of the ontouch method. We need to judge whether the delegate is an action protocol and whether there is a doaction method. This judgment is rigorous enough. If yes, call the doaction method of the action protocol.

    In fact, there is no need for screen to implement the Action protocol, although this is often the case in development. Any class instance that implements the Action protocol can be set to the delegate attribute of screen.

    The above example is not very similar to the situation encountered during development. The actual situation is often similar to the following example. First, let's look at the main method:

     
     
    1. #import <Foundation/Foundation.h>   
    2. #import "MyScreen.h"  
    3. int main (int argc, const char * argv[]) {   
    4.     NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];  
    5.     Screen *screen=[[MyScreen alloc] init];  
    6.     [screen onTouch];   
    7.     [screen release];   
    8.     [pool drain];   
    9.     return 0;   

    A myscreen class is added here. It inherits from the screen class. The code here does not set the delegate attribute, because it is already set in the init method of the myscreen class. You will see it later.

    The action protocol has not changed, but optional is added:

     
     
    1. #import <Cocoa/Cocoa.h> 
    2. @protocol Action <NSObject> 
    3. @optional   
    4. - (void) doAction;  
    5. @end 

    The screen class can be considered as an abstract class, which is mainly used for inheritance and reuse the code in the delegate mode. Header file:

     
     
    1. #import <Foundation/Foundation.h>   
    2. #import "Action.h"  
    3. @interface Screen : NSObject <Action> {   
    4.     id <Action> delegate;   
    5. }  
    6. @property(nonatomic,retain) id <Action> delegate;  
    7. - (void) onTouch;  
    8. @end  

    Implementation file:

     
     
    1. #import "Screen.h"  
    2. @implementation Screen  
    3. @synthesize delegate;  
    4. - (void) onTouch{   
    5.     NSLog(@"on touch …");   
    6.     if ([delegate conformsToProtocol:@protocol(Action)] &&   
    7.         [delegate respondsToSelector:@selector(doAction)]) {   
    8.         [delegate performSelector:@selector(doAction)];   
    9.     }   
    10.     NSLog(@"on touched.");   
    11. }  
    12. @end 

    The doaction method is not implemented here.

    The following shows the header file of the myscreen class:

     
     
    1. #import <Cocoa/Cocoa.h>   
    2. #import "Screen.h"  
    3.  
    4. @interface MyScreen : Screen {  
    5. }  
    6. @end 

    Implementation file of myscreen class:

     
     
    1. #import "MyScreen.h"  
    2. @implementation MyScreen  
    3. - (id) init{   
    4.     if (self=[super init]) {   
    5.         delegate=self;   
    6.     }   
    7.     return self;   
    8. }  
    9. - (void) doAction{   
    10.     NSLog(@"Bang!!!!!!!!!");   
    11. }  
    12. @end 

    Delegate mode using categories

    You can use category to implement the delegate mode. Or the above example. The following uses category to implement an example.

    Main method:

     
     
    1. int main (int argc, const char * argv[]) {   
    2.     NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];  
    3.  
    4.     Screen *screen=[[Screen alloc] init];  
    5.     [screen onTouch];   
    6.     [screen release];    
    7.     [pool drain];   
    8.     return 0;   

    The header file of the screen class:

     
     
    1. #import <Foundation/Foundation.h> 
    2. @interface Screen : NSObject {   
    3.     id delegate;   
    4. }  
    5. @property(nonatomic,retain) id delegate;  
    6. - (void) onTouch;  
    7. @end 

    In this example, property does not actually play a role.

    Implementation file:

     
     
    1. #import "Screen.h"  
    2. @implementation Screen  
    3. @synthesize delegate;  
    4. - (id) init{   
    5.     if (self=[super init]) {   
    6.         delegate=self;   
    7.     }   
    8.     return self;   
    9. }  
    10. - (void) onTouch{   
    11.     NSLog(@"on touch …");   
    12.     if ([delegate respondsToSelector:@selector(doAction)]) {   
    13.         [delegate performSelector:@selector(doAction)];   
    14.     }   
    15.     NSLog(@"on touched.");   
    16. }  
    17. @end  

    Here, if you run the Code, only the following logs will be printed:

     
     
    1. 2011-05-26 10:37:30.843 DelegateDemo[5853:a0f] on touch …   
    2. 2011-05-26 10:37:30.846 DelegateDemo[5853:a0f] on touched. 

    Enter the category code named screenaction and its header file:

     
     
    1. #import <Cocoa/Cocoa.h>   
    2. #import "Screen.h"  
    3. @interface Screen (ScreenAction)   
    4. - (void) doAction;  
    5. @end 

    Implementation file:

     
     
    1. #import "ScreenAction.h"  
    2. @implementation Screen (ScreenAction)  
    3.  
    4. - (void) doAction{   
    5.     NSLog(@"BANG!!!!!!");   
    6. }  
    7. @end 

    Execute the following code:

     
     
    1. 2011-05-26 10:37:30.843 DelegateDemo[5853:a0f] on touch …   
    2. 2011-05-26 10:37:30.846 DelegateDemo[5853:a0f] BANG!!!!!!   
    3. 2011-05-26 10:37:30.846 DelegateDemo[5853:a0f] on touched. 

    Summary:Objective-CLearning pathDelegateI hope this article will help you.

    Related Article

    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.