Protocol ):
<> To abide by an agreement, as long as it complies with this agreement, it is equivalent to having all the method declarations in the agreement.
- Declare a series of methods
- The compiler does not force the implementation of all methods in the Protocol.
- Both classification and Protocol can only declare methods, but cannot declare member variables.
- Nsobject is a base protocol.
Assume that a person wants to buy a ticket, but he is not empty. An agent is required to help him ask about the fare. How many tickets are there ~
Ticketdelegate. h indicates the method required by the proxy.
/// Ticketdelegate. h // Protocol application-proxy mode /// created by mekor on 14-8-30. // copyright (c) 2014 mekor. all rights reserved. // # import <Foundation/Foundation. h> // declare some running methods @ protocol ticketdelegate <nsobject> // return the fare-(double) ticketprice; // how many tickets are left-(INT) leftticketsnumber; @ end
Humans:
//// Main. M // Protocol application-proxy mode /// created by mekor on 14-8-30. // copyright (c) 2014 mekor. all rights reserved. // # import <Foundation/Foundation. h> # import "ticketdelegate. H "@ interface person: nsobject-(void) buyticket; // has a proxy property // ID indicates the proxy class name. // However, it must comply with the ticketdelegate Protocol @ property (nonatomic, retain) ID <ticketdelegate> delegate; @ end
/// Person. M // Protocol application-proxy mode /// created by mekor on 14-8-30. // copyright (c) 2014 mekor. all rights reserved. // # import "person. H "@ implementation person // buy a movie ticket-(void) buyticket {// ask the agent to buy a ticket for himself. Double price = [_ delegate ticketprice]; int number = [_ delegate leftticketsnumber]; nslog (@ "via proxy help, fare = % F, % d tickets left", price, number);} @ end
Proxy:
/// Agent. h // Protocol application-proxy mode /// created by mekor on 14-8-30. // copyright (c) 2014 mekor. all rights reserved. // # import <Foundation/Foundation. h> # import "ticketdelegate. H "@ interface agent: nsobject <ticketdelegate> @ end
/// Agent. M // Protocol application-proxy mode /// created by mekor on 14-8-30. // copyright (c) 2014 mekor. all rights reserved. // # import "agent. H "@ implementation agent // the remaining number of votes-(INT) leftticketsnumber {return 1;} // how much is each ticket-(double) ticketprice {return 1000;} @ end
Main. M file
1 // 2 // main. m 3 // Protocol application-proxy Mode 4 // 5 // created by mekor on 14-8-30. 6 // copyright (c) 2014 mekor. all rights reserved. 7 // 8 9 # import <Foundation/Foundation. h> 10 # import "person. H "11 # import" agent. H "12 INT main (INT argc, const char * argv []) 13 {14 15 @ autoreleasepool {16 person * P = [[person alloc] init]; 17 agent * A = [[Agent alloc] init]; 18 p. delegate = A; 19 [p buyticket]; 20} 21 return 0; 22}
Simple Protocol application-proxy Mode