How to use Delegate (delegate) in iOS

Source: Internet
Author: User
Tags event listener uikit

From the beginning to engage in OC work to now about 1 years, from the first contact OC "Agreement" does not understand, to the present code everywhere in the Commission, agreement, which sentiment a lot.

First of all, we should all understand that the Commission is a kind of agreement, as the name implies, is to entrust others to help themselves to do something. That is, when you do something inconvenient, you can create a delegate, so you can entrust others to help themselves to achieve what method. Secondly, I briefly summed up the role of the delegate I used to have two, one is the value of the transfer, one is the event. 1. The so-called value is often used in class B to pass one of their own data or objects to Class A, let a class to show or deal with. (Segmentation tight coupling, and code chunking often used) 2. The so-called event is what happens in Class A, and it tells the person who is concerned about it, that is, the object of the delegate, the object of the delegate to consider what should be done after the event. (This is often seen, for example, in asynchronous requests, interface events trigger data-layer changes, and so on) 3. Using delegate assignment, this method feels so that you can give yourself a complex value without exposing your attributes, and it's easier to manage the class, which is only called when you want someone else to assign you a value, which can be controlled. (for example, a delegate in TableView (Datesource) is common). Finally, I would like to share some tips and considerations when using the delegate. Experience: Delegate name to be accurate, as far as possible to see the name to know how to use. Delegate and notices are used somewhat like, but the former is single-to-single, the latter is a single-to-many situation. Note: In Dealloc to delegate to nil, there is delegate set the properties of the time to use assign, do not use retain. Delegate

The delegate is implemented in iOS in a @protocol way, so it is also called a protocol. A protocol is a list of methods that are shared by multiple classes, and the methods listed in the protocol do not respond to implementations that are implemented by others. It's better than I want to buy a cell phone, so I have a buyiphone method, But I don't know who buys a cell phone, so put that demand out (for example, on the website), and if there's a businessman selling a cell phone (which means he can achieve buyiphone), he will accept my Commission (<XXXdelegate> in the merchant's own class) , then my delegate object points to this businessman. When I want to buy a cell phone, I can just look for him.

For example:

@protocol mydelegate-(void) Buyiphone: (NSString *) Iphonetype money: (NSString *) money; @end @interface my:nsobject{    id<mydelegate> Deleage;} @property (assign,nonatomic) id<mydelegate> delegate; @end

The code declares a protocol called MyDelegate, in which there is a Buyiphone method, which is a delegate item. When I want to buy a mobile phone only need to call the Buyiphone method via delegate.

As follows:

-(void) willbuy{    [delegate buyiphone:@ "iphone 4s" money:@ "4888"];}

I don't have to care who is realistic. This delegate, as long as the class of the delegate is implemented, and Buyiphone is the method that must be implemented in the declaration of the delegate, you will be able to get the result.

For example, a business man realizes this Commission (implemented with <Mydelegate>)

#import <Foundation/Foundation.h> #import "My.h" @interface business:nsobject<mydelegate> @end

Then call the Buyiphone method in the @implementation business

#import "Business.h" @implementation business-(void) Buyiphone: (NSString *) Iphonetype money: (NSString *) money{    NSLog (@ "mobile phone has goods, this price sell you, delivery in!");} @end
Delegation is one of the simplest and most flexible patterns in cocoa. A delegate is a behavior that gives an object an opportunity to react to a change in another object, or to affect another object. The basic idea is that two objects work together to solve the problem. An object is very common and intended to be reused in a wide range of situations. It stores a reference to another object (that is, its delegate) and sends a message to the delegate at the critical moment. A message may simply notify the delegate that something has happened, give the delegate an opportunity to perform additional processing, or the message may require the delegate to provide some critical information to control what is happening. 4 days ago Upload download attachment (KB) The delegate method usually consists of 3 verbs: should, would, did. The
should indicates that an action occurs before, usually with a return value, that alters the state of the object before the action occurs. Will before the action occurs, the delegate can respond to the action, but without the return value. Did the response that occurred after the action was made.
from the definition of methods it is not difficult to see that the delegate model can play two roles:
First: The delegate assists the object body to complete an operation, and it will need to customize the operation through the delegate object to customize the implementation, to achieve and sub-class object body the same role. Second: Event listener, the delegate object listens to some important events of the object body, makes the concrete response to the event or broadcasts the event to the object that needs to respond.
Personal understanding of the advantages of using the delegate model is:
1, to avoid the subclass of the excessive subclass and the child class and the parent class coupling 2, the implementation of the hierarchical decoupling
Delegate mode through the message mechanism of the delegate:
1, usually a weak reference in the object body containing a delegate object: @ Interface a:nsobject {Iboutlet ID delegate;}-(ID) delegate;-(void) Setdele Gate: (id) obj; 2, the implementation of the delegate object has two ways: formal agreement and informal agreement, the object body defines the delegate method in the agreement, the delegate object can choose to implement some of these delegate methods, so if the formal agreement to define the delegate method needs to use @option. @protocol  nssearchdelegate @option-(void) Didsearchfinish: (* nsnotification) anotification; @end 3, the Connection object body and the delegate, is simply through Setdelegate: (ID) obj to achieve.
4, triggering the delegate method.

Yesterday did a demo, using a simple proxy.

Delegate is a design pattern for iOS programming. We can use this design pattern to let a single-inherited objective-c class exhibit the characteristics of a class outside its parent class. Yesterday this proxy implementation is as follows:

The class Gifview is inherited from UIView, and it loads on Rootviewcontroller to play the animation through a timer. At the same time, Rootviewcontroller needs to know every execution of the timer.

The code is as follows.

First, define the Gifview, define the proxy everyframedelegate in its header file, and declare the method-(void) dosomethingeveryframe;

#import <UIKit/UIKit.h> @protocol everyframedelegate <nsobject>-(void) dosomethingeveryframe;@ End@interface Gifview:uiview {    nstimer *timer;    ID <EveryFrameDelegate> delegate;    Nsinteger Currentindex;} @property (nonatomic, retain) ID <EveryFrameDelegate> delegate; @end

Then, just let the timer in the GIFVIEW.M call delegate to execute the Dosomethingeveryframe each time it executes, the code is as follows

-(ID) initWithFrame: (cgrect) frame{self        = [Super Initwithframe:frame];    if (self)    {        timer = [Nstimer scheduledtimerwithtimeinterval:0.05 target:self selector: @selector (play) Userinfo:nil Repeats:yes];        [Timer fire];    }    return self;} -(void) play{        [delegate dosomethingeveryframe];}

The work on the Gifview is done.

The following is the code in Rootviewcontroller, Rootviewcontroller can know every execution of a timer by specifying its proxy as itself when defining Gifview:

-(void) viewdidload{    [Super Viewdidload];    Additional setup after loading the view, typically from a nib.    CGRect rect = CGRectMake (0, 0, N, a);    Gifview *tmp = [[Gifview alloc] initwithframe:rect];    Tmp.delegate = self;    [Self.view addsubview:tmp];    [TMP release];} -(void) dosomethingeveryframe{    NSLog (@ "I ' m The delegate! I ' m doing printing! ");}

Every time a timer executes in a gifview, one line is printed

I ' m The delegate! I ' m doing printing!

So, Rootviewcontroller knew every time the timer was executed.

When you do a program, you often encounter a situation where you have an object B in object A, and you need to invoke a method of the A object when doing an operation in B. At this point, we need to use a proxy mechanism, also known as the delegation mechanism.

Remember when the first contact object-oriented, incredibly in the B object and alloc a object, found that the execution method is not works, then did not understand the new Alloc object and the original object A is not a thing. Today special tuition for a bit ha, on the internet to find some information, integrated a bit, wrote this rookie tutorial.

The principal agent (delegate), as the name implies, entrusts something to other objects to do. Then the other object is the agent of this object, instead of it to take care of what to do. Reflected in the program, the first thing to know is the object of the client is which object, the delegate is what the content. The delegation mechanism is used in many languages, this is just a general idea, there will be a lot of information on the Internet.

The following is a brief example of a delegate:

First, the new iphone project Delegatedemo;

Second, add UIView class Viewa;

Third, the contents of ViewA.h are as follows:

[CPP]View Plaincopy
  1. #import <UIKit/UIKit.h>
  2. @protocol <a href="http://www.wuleilei.com/" target="_blank" ><span style="color: #ff0000" > viewadelegate</span></a>; Declaration of Agency agreement
  3. @interface Viewa:uiview {
  4. ID <<a href="http://www.wuleilei.com/" target="_blank" ><span style="color: #ff0000" >  Viewadelegate</span></a>> _viewadelegate;
  5. }
  6. @property (nonatomic, assign) ID viewadelegate; //Define the properties of the agent and in the. M plus
  7. @end
  8. Content of the agent agreement
  9. @protocol <a href="http://www.wuleilei.com/" target="_blank" ><span style="color: #ff0000" > viewadelegate</span></a> <NSObject>
  10. -(void) <span style="color: #008080" >viewACallBack</span>;
  11. @end
  12. In VIEW.M:
  13. <span> </span> @synthesize viewadelegate = _viewadelegate;

Third, in the DELEGATEDEMOVIEWCONTROLLER.M:

-(void) Viewdidload {Viewa *viewa = [[Viewa alloc] Initwithframe:cgrectmake (+, +, +)];viewa.viewadelegate = self ; Set the Viewa proxy for the current object itself [Self.view Addsubview:viewa]; [Viewa release]; [Super Viewdidload];} -(void) Viewacallback {NSLog (@ "Hi, I am back!");}

Four

Click here to download the sample.

How to use Delegate (delegate) in iOS

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.