The data callback or proxy mode in IOS is mostly implemented by a callback function or block (code block), there is nothing to say about the block, syntax, here is a simple understanding of how the callback function works.
(This callback function works in fact the process of proxy mode.)
First, the implementation of the proxy class
First, create a new proxy class and write a protocol in it: Agencyprotocol
@protocol Agencyprotocol <nsobject>-(void) cometruesuccess: (NSString *) str; -(void) Cometruefail: (NSString *) str; @end
Then operate in the proxy class:
- Introduce the AGENCYPROTOCOL protocol and define a proxy for the Agencyprotocol Protocol (delegate);
- Use singleton mode for the proxy class (the General proxy class uses the singleton mode better, can prevent the memory leak);
- Implement an Agent method;
. h File Code:
@protocol Agencyprotocol; @interface IDdelegate; // Singleton mode + (ID) shareinstance; /* * * Analog Proxy method * * @param str Indicates the parameters passed in * */-(void) Agencyfunction: ( NSString *) str andbool: (BOOL) Isbool; @end
. m file Code:(the proxy implementation here is the most important part of the callback function)
@implementationAgencyclass#pragmaMark-Singleton modeStaticAgencyclass *instnce;+ (ID) shareinstance {if(Instnce = =Nil) {instnce= [[[Selfclass] [alloc] init]; } returninstnce;}#pragmaMark-Proxy implementation-(void) Agencyfunction: (NSString *) str andbool: (BOOL) Isbool {if(isbool) {//call the Respondstoselector method to determine if the cometruesuccess is implemented and implement it if it is not implemented if([Self.Delegaterespondstoselector: @selector (cometruesuccess:)]) {[Self.DelegateCOMETRUESUCCESS:STR]; } } Else { //call the Respondstoselector method to determine if the Cometruefail is implemented and implement it if it is not implemented if([Self.Delegaterespondstoselector: @selector (cometruefail:)]) {[Self.DelegateCOMETRUEFAIL:STR]; } }}@end
Second, the implementation of the use of the class
First, we introduce the proxy class in the. h file, and introduce the Protocol
#import " AgencyClass.h " @interface viewcontroller:uiviewcontroller<agencyprotocol>@end
Then we can manipulate in. m files
- Create an object for the proxy class;
- The delegate that will be used to assign the class to the proxy class;
- Using proxy methods
// using proxy classes // creating an Object for a proxy class Agencyclass *agency = [Agencyclass shareinstance]; // The delegate that will be used to assign the class to the proxy class; Agency. delegate = self ; // using proxy methods [Agency agencyfunction:@ " really in the implementation?" [ Andbool:yes];
The last two ways we can implement a protocol
#pragma mark-agencyprotocol implementation-(void) cometruesuccess: (NSString *) str { NSLog (@ " %@ Yes, the operation was successful! ", str);} -(void) Cometruefail: (NSString *) str { NSLog (@ "%@ Sorry, the operation failed " , str);}
IOS-use of callback functions