The use of delegate in IOS

Source: Internet
Author: User

I have been engaged in OC work for more than a year now, and I have learned a lot from the "protocol" that I first came into contact with OC, to the delegation and protocols that can be seen everywhere in the code.

First, we should understand that delegation is a type of agreement. As the name suggests, it is to entrust others to do something for themselves. That is, when it is not convenient for you to do anything, you can establish a delegate so that you can entrust others to help you implement what methods. Secondly, I briefly summarized the two roles of the delegate I used: value transfer and event transfer. 1. The so-called value transfer is often used in Class B to pass one of its own data or objects to Class A for Class A to be displayed or processed. (Splitting is tightly coupled and often used when code is segmented) 2. the so-called transfer event is what happened to Class A. Tell the person who pays attention to the event, that is, the delegate object, it is the delegate object to consider what reflection should be made after this event occurs. (This is often seen, for example, in asynchronous requests, interface events trigger data layer changes, etc.) 3. using delegate assignment, we feel that we can re-value ourselves without exposing our own attributes, and this makes it easier to manage classes, this assignment can be called only when you want others to assign values to you. (For example, a delegate (datesource) in tableview is common ). Finally, I would like to share some of my experiences and considerations when using delegation. TIPS: the name of the delegate should be accurate, and the name should be used as far as possible. Some delegate and notifications are used in some ways, but the former is single-to-single, while the latter is single-to-many. Note: In dealloc, set delegate to nil, and use assign instead of retain when setting attributes of delegate. Delegate

In iOS, delegation is implemented through a @ protocol method, which is also called a protocol. the Protocol is a list of methods shared by multiple classes. The methods listed in the Protocol have no response implementation, and are implemented by others. this is like buying a mobile phone, so I have a buyiphone method, but I don't know who is buying a mobile phone, So I release this requirement (such as posting it on a website ), if a mobile phone seller (that is, he can implement the buyiphone method) sees it, he will accept my commission (implement <xxxdelegate> in the merchant's class ), then my delegate object points to this merchant .. when I want to buy a mobile phone, just look for him directly.

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 named mydelegate, in which there is a buyiphone method, that is, a delegate. When purchasing a mobile phone, you only need to call the buyiphone method through Delegate.

As follows:

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

I don't have to worry about who has implemented this delegate. As long as the delegate class is implemented and the buyiphone is a required method in the delegate declaration, the result will surely be obtained.

For example, Shang human has implemented this delegate (expressed by <mydelegate>)

#import <Foundation/Foundation.h>#import "My.h"@interface Business : NSObject<MyDelegate>@end

Then call the buyiphone method in @ implementation business.

# Import "business. H "@ implementation business-(void) buyiphone :( nsstring *) iphonetype money :( nsstring *) money {nslog (@" mobile phone is available, this price is sold for you, and it is being shipped !! ");} @ End
Delegation is one of the simplest and most flexible modes in cocoa. A delegate is an action that gives an object the opportunity to respond to changes in another object or affect another object. The basic idea is to coordinate two objects to solve the problem. An object is very common and intended to be reused in a wide range of scenarios. It stores references pointing to another object (that is, its delegate) and sends messages to the delegate at critical moments. A message may only notify the delegate that something has happened, giving the delegate the opportunity to perform additional processing, or the message may require the delegate to provide some key information to control what happened.
The attachment upload/download (18 Kb) delegation method four days ago usually includes three kinds of verbs: shocould, Will, and did.

Shocould indicates that an action usually has a return value before it occurs, and the object state can be changed before it occurs.
Prior to an action, the delegate can respond to the action without returning the value.
Did response after an action occurs.

From the definition of methods, we can easily see that the delegated mode can play two roles:

1. Delegate assistance to the object subject to complete an operation, and customize the operation by entrusting the object to customize the implementation, so as to play the same role as the subclass object subject.
Second, event listening: The delegate object listens to some important events of the object subject, and makes a specific response to the event or broadcasts the event to the objects needing a response.

The advantage of the delegated mode is:

1. Avoid the excessive subclass caused by subclass and the coupling between subclass and parent class.
2. Hierarchical decoupling through the message delivery mechanism

How to Implement the delegation mode:

1. Generally, the object body contains a weak reference of a delegate object:
@ Interface A: nsobject
{
Iboutlet ID delegate;
}-(ID) delegate;
-(Void) setdelegate :( ID) OBJ;
2. There are two ways to implement the delegate object: formal and informal. The object subject defines the delegate method in the Protocol. The delegate object can choose to implement some of the delegate methods, therefore, if you use the formal protocol to define the delegate method, you need to use @ option.
@ Protocol nssearchdelegate
@ Option
-(Void) didsearchfinish :( * nsnotification) anotification;
@ End
3. The connection object subject and delegate are implemented by setdelegate :( ID) obj.

4. Trigger the delegate method.

Yesterday I made a demo and used a simple proxy.

Delegate is a design mode for iOS programming. We can use this design pattern to show the characteristics of a class outside its parent class for a single inherited objective-C class. The proxy implementation yesterday is as follows:

 

The class gifview is inherited from the uiview, And it is loaded on the rootviewcontroller to play an animation through a timer. At the same time, rootviewcontroller needs to know every execution of timer.

The Code is as follows.

First, define the gifview, define the proxy everyframedelegate in the 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, as long as timer calls delegate to execute dosomethingeveryframe in gifview. m, 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 gifview is complete.

The following is the code in rootviewcontroller. As long as rootviewcontroller specifies its proxy as itself when defining a GIF view, it can know every execution of Timer:

- (void)viewDidLoad{    [super viewDidLoad];    // Do any additional setup after loading the view, typically from a nib.    CGRect rect = CGRectMake(0, 0, 200, 200);    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!");}

In gifview, Timer prints a row each time it is executed.

I'm the delegate! I'm doing printing!

Therefore, rootviewcontroller knows every time timer is executed.

During program creation, we often encounter the following situation: Object A contains object B, and a method of object A needs to be called when performing an operation in object B. In this case, we need to use a proxy mechanism, also called a delegation mechanism.

I still remember that when I first got started with object-oriented, I actually alloc another a object in object B and found that there was no works in the execution method, at that time, I didn't understand that the new alloc object and the original object A were not a thing.
Today, I learned a little about it and found some information on the Internet. After a comprehensive look, I wrote this cainiao tutorial.

A delegate proxy, as its name implies, delegates what an object wants to do to other objects. So other objects are the proxies of this object, instead of them to take care of what to do. To be reflected in a program, you must first specify the object that the principal of an object is and what the principal is doing. The delegation mechanism is used in many languages. This is just a general idea. There will be many introductions on the Internet.

The following is a simple example of delegation:

1. Create the iPhone project delegatedemo;

2. Add the uiview class viewa;

Iii. Content of viewa. H is as follows:

# Import <uikit/uikit. h> @ protocol viewadelegate; // declare the proxy Protocol @ interface viewa: uiview {id <viewadelegate> _ viewadelegate;} @ property (nonatomic, assign) ID viewadelegate; // define the attributes of the agent. M adding @ end // proxy protocol content @ protocol viewadelegate <nsobject>-(void) viewacallback; @ endview. m: @ synthesize viewadelegate = _ viewadelegate;

3. In delegatedemoviewcontroller. M:

-(Void) viewdidload {viewa * viewa = [[viewa alloc] initwithframe: cgrectmake (50,100,200,100)]; viewa. viewadelegate = self; // sets the proxy of viewa as the current object [self. view addsubview: viewa]; [viewa release]; [Super viewdidload];}-(void) viewacallback {nslog (@ "Hi, I am back! ");}

IV,

Click here to download the example.

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.