In real life we have a variety of agreements, but all have one thing in common, is the proposed agreement, we must abide by, non-compliance is a breach of contract. There is also the concept of agreement in OC and is similar to the characteristics of our real-life agreements. Sometimes we want to do something ourselves, but now we do not have the ability to do it ourselves, we need to find an agent to help us do. Then there is the concept of proxy in OC. Here's a brief talk about the protocols and proxies in OC.
First, the agreement
A way of interacting with an object is implemented in the interaction of the iOS development Objective-c object. There are other ways in OC, such as protocol, which uses protocols in OC to standardize interfaces, and is a mechanism for interacting between objects. Similar to the interface in Java. You can also simulate multiple inheritance.
Implementation of the Protocol The first step: use Xcode to create a new project;
How to create a new project "iOS Development objective-c" new first project-helloworld ".
Step Two: Create a new OC file;
In this project the New file-----> objective-c File-----> Fill in the File name –> select "Protocol" in the file Type and finally click Next.
Step three: "formulating" the agreement;
Suppose I sign with someone and an agreement that requires me to perform an action: one hour a day to practice OC programming; Then the agreement is:-(void) adaycodeonehour; this is just an agreement clause, and the agreement itself is not capable of complying with the Agreement or implementing the agreement.
#import <Foundation/Foundation.h> @protocol myprotocol <NSObject>-(void) adaycodeonehour; @required //default property must be implemented-(void) show;//show is required to implement @property (nonatomic,assign) int A; @optional //Optional implementation-(void) Show1; Show1 can be implemented or not implemented @end
Fourth step: abide by the agreement;
Create a new person class in this class. m file to implement this method. Before implementing it, you need to show why you are implementing this method. Then we need to show in the person class that I am following this agreement. We need to indicate in the class's. h file that I am complying with this agreement.
#import <Foundation/Foundation.h> #import "MyProtocol.h" @interface person:nsobject <myprotocol>@ Property (nonatomic,assign) int A; @end
Here we have to do two things, the first is to wrap the protocol this header file, the second is @interface Person:nsobject <MyProtocol>. The next step is the implementation of the Protocol. In person.m this file we simply implement:
#import "Person.h" @implementation person-(void) adaycodeonehour{ NSLog (@ "My protocol content is" practice one hour per day OC Programming ");} -(void) show{ NSLog (@ "This is an example of a protocol. ");} @end
Fifth Step: Demo in main function
#import <Foundation/Foundation.h> #import "Person.h" int main (int argc, const char * argv[]) { @autoreleasepool {Person * PS = [[Person alloc] init]; [PS Adaycodeonehour]; The default is also necessary to implement the [PS show],//Call @required modification of a method PS.A = 10;//Assign a value NSLog (@ "%d", PS.A);//Take the value of a to print out id< Myprotocol>obj = PS; Using the Di method indicates that obj is an object ps [obj Show];//obj also calls show this method } return 0;}
We have a few words in the agreement myprotocol that are not stated:
@required // default property, you must implement the
-(void) show; //show is necessary to achieve
@property (nonatomic,assign) int A;
@optional // an optional implementation
-(void) Show1; //show1 can be implemented or not implemented in the L example
@required The default property, the method that he modifies must be implemented;
@optional Optional attribute, the method that he modifies can not be implemented
We cannot declare variables in the protocol, but we can use the methods of attributes:
@property (nonatomic,assign) int A;
In the protocol compliance party to achieve this, but also in the. h file paste some of this statement, the system will automatically give us the production of set and get method.
The main function is relatively simple, but you need to learn this sentence:
ID<myprotocol>obj = PS; // using the ID method indicates that obj is a copy of the object PS
[obj show]; //obj also called Show This method
ID of this sentence, where an ID class is used to comply with the MyProtocol protocol object obj, so that the object and the object PS point to the same piece of memory area.
How to simulate multiple inheritance?
In fact, it is not difficult for us to achieve < Agreement 1, agreement 2 >. In fact, in the system library there are a lot of such wording. I'm not going to write about it here.
Second, agent mode what is an agent?
A proxy pattern is a mechanism for implementing the interaction between two objects. There are two objects involved in the proxy mode, one is the active side and the other is the passive side.
Proactive: Draw up an agreement to create an ID pointer with an agreement (pointing to a specific agent);
Passive side: Abide by the protocol, implement the method of the Protocol.
Life situation
Now what delivery is very much, every day there are many bills on the road. We don't want to buy food, we can order takeout. Can we designate which one to eat? We also can not say take the takeout not to give money, we also need to pay merchants. Four questions are involved here. Which meal do I buy? What kind of food do I buy? I want to pay the seller. The seller needs to get his meal. This is a few steps after the situation is dismantled.
①. Buyer's demand: I want to eat, what kind of food to eat?
②. Buyers choose shop and eat what;
③. Sellers send meals to buyers;
④. Buyer pays the seller;
⑤. The seller gets his meal money.
Implementation of the Agent
With these steps, it is not difficult to implement them.
#import <foundation/foundation.h>//@protocol buyfood <nsobject>-(void) sendfood;//sellers to deliver meals in the active party-(void) Getmoney: (int) money;//sellers get meal @end@interface person:nsobject-(void) Wanttoeat: (NSString *) food;//buyers want to eat what Rice-( void) give: (int) money;//How much does the seller give the seller//Declare a property with a protocol pointer @property (nonatomic,assign) id<buyfood>delegate; @end
#import "Person.h" @implementation person-(void) Wanttoeat: (NSString *) food{ //Choose what to eat NSLog (@ "Customer: I want to eat%@", food ); [Self.delegate Sendfood];} -(void) give: (int) money{//Buyer Payment //Note here the self.delegate [self.delegate Getmoney:money];//payment to the seller who sent me the meal} @end
#import <Foundation/Foundation.h> #import "Person.h" @interface rooom:nsobject <buyfood>-(void) show;-( void) Wanttogetmymoney; @end
#import "Rooom.h" @implementation rooom{int _money;} -(void) sendfood{//Seller delivery NSLog (@ "Store: OK I'll give you a quick delivery");} -(void) Getmoney: (int) money{_money = money;//The seller gets the meal and puts it in his own pocket.}-(void) wanttogetmymoney{//sellers want to buy a meal you need buyer to pay buyer payment to the corresponding Seller//Here is the callback person for the agent * p1 = [[Person alloc] init]; P1.delegate = self; Note here that the self who calls this method is who [P1 give:15]; Give is the active method buyer pays 15 Yuan}-(void) show{NSLog (@ "Store: I got my money:%d", _money);} @end #import <Foundation/Foundation.h> #import "Person.h" #import "Rooom.h" int main (int argc, const char * argv[]) { @autoreleasepool {person * per = [[Person alloc] init]; Rooom * Roo = [[Rooom alloc] init]; [per wanttoeat:@ "Fish fragrant shredded pork rice"]; I want to eat fish fragrant pork rice per.delegate = roo; Specify proxy settings Agent selection shop [Roo Sendfood]; Seller delivered meal [Roo Wanttogetmymoney]; Buyer pays the seller to get the meal [Roo show]; Happy sellers say I got how much money}return 0;
Output:
2015-08-03 21:41:15.656 3. Proxy mode [3,528:303] Customer: I want to eat fish fragrant pork rice 2015-08-03 21:41:15.673 3. Proxy mode [3,528:303] Store: OK, I'll send you the 2015-08-03. 21:41:15.674 3. Proxy mode [3,528:303] shopkeeper: I got my money:15.
Program ended with exitcode:0
This is all the code for this scenario pattern. There are protocols, there are proxies and callbacks. Every step is done. There is analysis, and there are comments in the code.
Let's analyze it again:
①. Buyer's demand: I want to eat, what kind of food to eat?
②. Buyer choose Shop and what to eat//buyer Choose Shop Designate Agent
③. Seller to send food to buyer;//the seller needs to make the agreement after the selected store
④. The buyer pays the seller;//Send value forward value to the agent the buyer pays the seller
⑤. The seller gets his meal money. Agent callback sellers need to get a meal from a buyer
Callback for Proxy
Proxy callback: Call a function module, this function module returns some data, but the function does not know exactly which object to return to, at this time, we can pass the protocol specification receiver to receive data method, this process is callback.
The proxy callback is also available in the above scenario, as well as the code above.
Iii. Summary
Through the specific examples above, we need to know what is a protocol? What is an agent? The connection between the agreement and the agent. How to implement a simple protocol, or what is the basic format of a protocol? What is the basic format of the agent? How does the agent callback?
Of course, the above examples and code is not enough to make me deepen the understanding of the agreement and agent, but also I need to work and learn more summary, theory and practice.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"iOS Development objective-c" protocol and Agent