1. Preface
Since the end of May this year after the official transfer of iOS, get new skills every day, a lot of skills in the brain to maneuver not to vomit, so, write something to tidy up a bit. Start with the protocol agent first.
2. Declaration of the method of agreement
@protocol Eventmenubardelegate <nsobject>-(void) delegateshoulddowhenmenubuttontapped: (UIButton *) button ; @end
The code above means that the @protocol directive declares the protocol name Eventmenubardelegate and complies with the NSObject protocol, declaring a method in the Protocol
-(void) delegateshoulddowhenmenubuttontapped: (UIButton *) button, since it is not declared with the @option Directive, So the object that obeys the Eventmenubardelegate must implement delegateshoulddowhenmenubuttontapped: This method.
3. Understanding of the Protocol agent
The method declared in the protocol, in fact, is the abstract method of object-oriented programming language such as C + +, does not need to implement the process, but must declare the method interface to be used to inherit the subclass of the class to adapt, this is the design mode of the adapter mode. In Objective-c, subclasses achieve the multi-inheritance effect of C + + by adhering to the protocol and inheriting the superclass. I think the advantage is that polymorphism.
4. Scenario Simulation and code implementation
A delegate agent is actually another object that an object needs to complete one of the methods it is looking for. For example, I am a lazy person, I do not like to wash clothes, I find a laundry assistant to help me wash, at this time, the Assistant is my laundry agent , and must comply with the washing protocol and to achieve the process of washing clothes. After the assistant washed, I thanked the assistant as the assistant agent and said thank you and paid for it. (a bit around, need a big hole in the brain) if the program implementation can be written as follows. In fact, in this scenario, the code simulates two delegate agents, One is the protocol agent for the laundry service, and the other is the protocol agent for the entire business logic.
1) The protocol method of washing clothes
#import <Foundation/Foundation.h>#import"APPBLLDelegate.h" @protocol Washclothes <nsobject>-(void) Washclothes: (int) num Complete: (ID< appblldelegate>)delegate; @end
The code declares the protocol of the laundry suit, and all objects complying with the protocol must do one thing according to the number of incoming clothes to wash clothes, after washing agent I (agent) to respond to the processing.
2) Business Logic Protocol
@protocol Appblldelegate <nsobject>-(void) Didwashclothessuccess: (BOOL) finished leftnum: (int) Left; -(void) didwashclothefailed: (NSString *) errormsg; @end
Business logic in the Protocol, the Declaration of two methods, one is the laundry after the success I need to do, and the other is not successful laundry I need to do. In fact, here can be completely abstracted into any event of the Protocol method, a different name. For example, a network request response, a database read library write library.
And as the business logic of my (agent), when the laundry assistant to me when the agent parameter passed in, not sure of my type, only as an ID type of object pointer passed in, but I must follow the Appblldelegate protocol, that is,
(id<appblldelegate>) Delegate
3) I (user) of the Class Code implementation
Header file
#import <foundation/foundation.h> #import washclothes.h " #import " appblldelegate.h @interface User:nsobject <appblldelegate> @property int Clothesnum; @property (weak, nonatomic) id <WashClothes> delegate ; -(void @end
My laundry agent is the assistant, the assistant class is not necessarily what class, I am not sure, so use the ID type to refer to its type (of course, if it is OK to specify the class name is good), but the assistant must follow the washing protocol, that is,
Id<washclothes> delegate
And I, as the agent of the entire business logic, I also have to follow the protocol of the business logic (bigger point in the brain hole). That
User:nsobject <APPBLLDelegate>
Implementation file
#import "User.h"@implementationUser- (void) askassistantforwashingclothes {[Self.DelegatewashClothes:self.clothesNum complete:self];}- (void) Didwashclothessuccess: (BOOL) finished Leftnum: (int) left {if(finished) {NSLog (@"Assistant has finished washing clothes, thank you, pay the laundry fee"); } Else{NSLog (@"Assistant failed to wash clothes, left%d pieces", left); }}- (void) didwashclothefailed: (NSString *) errormsg {if(ErrorMsg! =Nil) {NSLog (@"Error:%@", errormsg); }}@end
I do not wash clothes, I ask the assistant to wash clothes, then the assistant must follow the laundry agreement, and implement the specific process, but I do not need to implement, my task is only to send a laundry message to the agent. When my assistant finishes the laundry, I am acting as the business logic agent, and I have to respond, for example, I want to say thank you for the money, or not to pay for the washing, or if there is a problem I want to error.
Here, the business logic can be abstracted as a network request, for example, the network is in good condition, I request the success, correctly pass the parameter, return correctly. Or, the network is in good condition, the error is passed, and the error is returned. Or, the network condition slag, error it.
4) The laundry assistant has to do
Header file
#import <Foundation/Foundation.h>#import"WashClothes.h"@ Interface assistant:nsobject <WashClothes>int totalnum; - (instancetype) init; @end
The Laundry assistant must follow the laundry agreement, i.e.,
Assistant:nsobject <WashClothes>
Implement the laundry method, i.e.,
-(void) washclothes: (int) num Complete: (id<appblldelegate>) delegate;
Implementation file
#import "Assistant.h"@implementationAssistant-(instancetype) init { self=[Super Init]; if(self) {self.totalnum=Ten; } returnSelf ;}- (void) Washclothes: (int) Num Complete: (ID<APPBLLDelegate>)Delegate { intleft = Self.totalnum-num; if(Left >0) { [DelegateDidwashclothessuccess:yes Leftnum:left]; } Else { [DelegateDidwashclothessuccess:no Leftnum:abs (left)]; [DelegateDidwashclothefailed:@"failed to finish washing clothes! "]; }}@end
Laundry Assistant when initializing the object, the default maximum number of washing clothes is 10 pieces, and realize the specific process of washing clothes, after washing the clothes to me (business logic agent) to send messages. In other words, the laundry assistant only needs to wash clothes, do not need to do anything to wash the clothes, the rest of the results back to me, let me do the message feedback.
5) Procedure Single entry
#import<Foundation/Foundation.h>#import "User.h"#import "Assistant.h"intMainintargcConst Char*argv[]) {@autoreleasepool {User*user =[[User alloc] init]; User.clothesnum= -; Assistant*assistance =[[Assistant alloc] init]; User.Delegate=assistance; [User Askassistantforwashingclothes]; } return 0;}
The main program created an instance of me, set my laundry quantity to 20, create an assistant instance, set up my laundry agent as an assistant, and finally send a message to the assistant to perform the laundry this way.
6) Running Results
2015-07-23 11:34:07.869 nydelegatetest[1313:68830] Assistant failed to wash clothes, remaining ten pieces
2015-07-23 11:34:07.870 nydelegatetest[1313:68830] Error: Failed to finish washing clothes!
5. Summary
1) OBJECTIVE-C protocol can implement the adapter mode, through inheritance and adherence to the Protocol, to achieve the multi-inheritance effect of C + +. Through this mechanism can realize the adaptation of multi-sub-class, so that different sub-classes have their own unique methods to match their own needs.
2) When implementing the Protocol proxy code, you must set the proxy for the instance, for example,
User.delegate = assistance;
This sentence is necessary, otherwise, the agent is nil, send the message is invalidated, the method cannot be executed, there will be no output.
3) In this simulation scenario, the code implements two protocol proxies.
One is, I'm looking for an assistant as my laundry agent.
The other is that when the assistant finishes washing, it passes the results back to me (business logic agent).
4) at the beginning of self-study, I always confused, table view of the data source and delegate. Now we understand that both are protocol agents, but the names are different. The method of data source is primarily loaded for display on some UI data sources for table view. And delegate is more of a response to some of the operation of Table view (but there are also some protocol methods such as height, I am drunk, obsessive-compulsive disorder). In summary, if you create a table view separately instead of using Table view Controller,data source and delegate must be set and implement its Protocol method.
5) If the article is misunderstood, please message exchange, I will revise in time, thanks ~
6) After coming to Shanghai, I grew up in two months, learned a lot, very grateful. I want to be proficient in the application of what I have learned, and to understand its principles in depth, so I have to learn a lot. But now it's much more calm. Lifelong learning, happy learning. Thank you for helping me everyone @ I do not know the Frost dance sad udspj @tinyfool, my beauty leader @ seven a six. Come on, I can do better!
iOS Development Summary--understanding of protocol agent