the relationship between delegate and protocol in iOSCategory: IOS development2014-02-12 10:47 277 People read Comments (0) favorite reports Delegateiosprocotolcategoryobject-c
Just beginning to touch iOS, the two concepts of delegate, protocol are blurred. Reference to some of the information, recorded experience.
1.protocol protocol and interface are similar concepts and are part of the OBJECT-C syntax. Protocol is a list of methods that do not belong to any class. The methods declared therein can be implemented by any class. Behavior is defined only in protocol, and different implementations are used in different situations. This pattern is generally referred to as the proxy mode. In iOS and OS X development, Apple employs a number of proxy models to achieve the decoupling of view and controller in MVC. How do you define protocol? In the declaration file (H file) is defined by the keyword @protocol, then gives the name of protocol, the method list, and then uses @end to represent the protocol end. The method defined before the end of the @end directive belongs to this protocol.
@protocol MyProtocol <NSObject> @required-(int) add: (int) A and: (int) b; @optional-(int) minus: (int) A and: (int) b;@ End
There are also two keywords, @required and @optional, one that must be implemented and one that is optional. Can be judged directly by name. How to use this protocol?
@interface text:nsobject<myprotocol> @end
Define a class to use protocol, surrounded by angle brackets (<...>) is our defined protocol, if you want to take more than one protocol, you can introduce multiple protocol names within angle brackets, separated by commas. Implement the method in the implementation file for this class:
@implementation text-(int) add: (int) A and: (int) b{ return a + b;} -(int) minus: (int) A and: (int) b{ if (a >= b) {return a-a ; } else return b-a;} @end
iOS protocol is similar to interface in the Java language, if there are no inheritance relationships between classes, but with some of the same behavior, You can use protocol to describe their relationships. Different classes can follow the same protocol, inject different instances under different scenarios, and implement different functions. This pattern is used extensively in the cocoa framework to achieve separation of data and UI. For example, all events generated by UIView are entrusted to the controller. According to the Convention, the framework suffix delegate is protocol, such as Uiapplicationdelegate,uiwebviewdelegate. 2.delegate Delegate and protocol It doesn't matter, Delegate itself should be called a design pattern. is to take one part of a class that you need to do, so that another class (or itself) can do it. When you execute a method of a class, you want to jump to another class in this method to execute another class, you can set the delegate to a different class. For example: If I want to know the results of an NBA game and the stats of my favorite stars while I'm at work, but I'm working, I can't do anything unrelated to my job, I can choose to send a message to two people, Let them check the results. Tell me, one to check the results of the game, one to check the data like the star, and then I continue to work. After a while, the two of them found what they wanted and returned it to me (to inform me). Then these two people are my different delegate objects. I. Delegate = sb. How to use delegate: Start with the example described above: First define a proxy class Person1 person.h as follows :
#import <UIKit/UIKit.h> @protocol querydelegate <nsobject>-(NSString *) query; @end @interface Person1: Uiviewcontroller<querydelegate> @end
Person.m
-(NSString *) query{ NSString * result = [NSString stringwithformat:@ "Heat wins the Sun: 103:98"] ; return result; }
First, the protocol and method are defined, the proxy class Person1 follows this protocol, and the delegate method is implemented. Also defines a proxy class person2,person2.h
#import <UIKit/UIKit.h> #import "Person1.h" @interface person2:uiviewcontroller<querydelegate> @end
Person2.m
-(NSString *) query{ nsstring * Data =[nsstring stringwithformat:@ "James ' figure is 37 points 9 rebounds 3 assists"]; return data;}
The proxy class Person2 also follows a protocol and implements the delegate method. We added two buttons and labels to the interface and asked to click on the button above to display the results of today's NBA heat vs. Sun game on the label below it. When you click on the button below, the following lable will show James ' data for today's game, add the interface, set the action to two labels for the two button, set the Outlet,ok, and then the interface as follows: DelegateViewController.h:
#import <UIKit/UIKit.h> #import "Person1.h" #import "Person2.h" @interface Delegateviewcontroller: Uiviewcontroller@property (weak,nonatomic) id<querydelegate> delegate;//declaration delegate-(IBAction) button1Action :(ID) sender;-(ibaction) Button2action: (ID) sender; @property (weak, nonatomic) Iboutlet UILabel *labelresult; @property (Weak, nonatomic) Iboutlet UILabel *labeldata; @end
See below DELEGATEVIEWCONTROLLER.M:
#import "DelegateViewController.h" @interface Delegateviewcontroller () @end @implementation Delegateviewcontroller@synthesize labeldata; @synthesize labelresult;.....-(Ibaction) Button1action: (ID) Sender { Person1 *pe1 = [[Person1 alloc] init]; Self.delegate = pe1;//Sets the proxy object to Person1 nsstring * result = [Self.delegate query];//invokes the delegate method through a delegate variable [labelresult Settext:result];} -(Ibaction) Button2action: (ID) Sender { Person2 *pe2 = [[Person2 alloc]init]; Self.delegate = pe2;//Sets the proxy object to Person2 nsstring* data = [self.delegate query]//Invoke delegate method via delegate variable [labeldata setText: Data]; }
The main thing to do in this step is to declare the delegate variable, set the proxy, and invoke the delegate's method through the delegate variable. Executive results: The delegate concept: The classic statement given in the first reading: 1.The main value of delegation is the it allows you to E Asily Customize the behavior of several objects in one central object.
The principal value of a delegate is that you can customize the functionality of multiple objects in a core object.
2. Build Helper Object Tool helper object is commonly used to add functionality to an existing class without have to subclass It.
Building helper Object,helper object is used to add functionality to an existing class instead of inheriting the implementation through subclasses. The following reprint a personal think to delegate more classic explanation, the original address: Click to open the link delegate itself should be called a design pattern. is to take one part of a class that you need to do, so that another class (or itself) can do it.
Like CLASSC.
@interface ClassC { ID delegate;} @end
First, define a variable of type ID, named delegate. Then the CLASSC implementation (. m file) can be used to delegate this variable. Of course, it is possible to use other names instead of delegate. We can also write this:
@interface ClassC { ClassB *delegate;} @end
So we know that delegate is a CLASSB, it can provide CLASSB in the method. You can put a part of CLASSC work in the CLASSB to achieve. Does this look a little strange? Or should it be written like this?
@interface ClassC { ClassB *classb;} @end
....... According to the above writing, delegate will not have. So in fact, delegate is only a model, we have a conventional, when the internal part of the realization of exposure to another class to do, it is called the actual work of the class for delegate. Why do we need to make an internal implementation for another class? The most common purpose is to provide a custom opportunity in the context of hidden implementations. For example, there are many delegate in the iOS SDK provided by Apple, such as the most commonly used uitableview, and we have no way of knowing how Apple can reuse UITableViewCell, how to deal with the increment and deletion of cell in UITableView, Because we have no source code. But we can control some of the behavior of a UITableView by implementing delegate methods. Uitableviewdatasource in fact, and delegate is the same, just because of the meaning of different changed a name. What role does protocol play here?
Protocol is a syntax that provides a handy opportunity to implement delegate patterns.
For example, when writing UITableView, Apple is doing this uitableview.m:
-(void) dosomething {[Self blahblah];[ Self.delegate guruguru];//into delegate to execute the Guruguru function [self blahblah];}
Delegate is the class we write, if this class can be passed to UITableView as its delegate, the only requirement is that it implements the
-(void) Guruguru;
This method. If we define this method in a protocol,
@protocol Xxxprotocol-(void) Guruguru; @end
It shows that the delegate required by UITableView is a conform to Xxxprotocol class. This is precisely the meaning of id<xxxprotocol> expression. No matter what the specific class is, it has other methods, as long as it conform to this protocol, it can be passed to UITableView, As the delegate of it. So Apple changed Xxxprotocol to Uitableviewdelegate in order to let us know that this Protocol is delegate needs conform protocol. so we see protocol's name with delegate, we know that this protocol function is used for custom (customization). Delegate is a pointer to another object, by MVC generally the best assignment object is the controller, which implements a pattern, which is not itself a pattern. Protocal is the definition of a set of methods. When id<protocal> is defined as delegate, it is necessary to use the other object is the assignment of delegate to implement the method in Protocal, this process uses the mode is the proxy mode. Delegate class +protocal will ensure that you implement the delegate class inside must have this delegate method, but as for the delegate class can also do other things.