In the previous article, I briefly introduced how to implement delegation.
In the location framework, the delegate and protocol are used together to implement decoupling and flexibility between objects. Now, based on the previous code, a new protocol is added, namely, managerdelegate, this Protocol has only one method decideframedescription, which constitutes a delegate mechanism (a design pattern ).
Code (Click here to download)
// Environment
// Mac OS X 10.3.7
// Xcode version 4.3.2 (4e2002) upgraded the new version of xcode for iOS 5.1
// Nsobject * in the code can be replaced by the ID type
# Import <Foundation/Foundation. h> @ protocol managerdelegate <nsobject> // protocol-(bool) decideframedescription; @ end
Use delegate to implement this Protocol, that is
@ Interface delegate: nsobject <managerdelegate> // bind mangerdelegate @ property nsinteger number;-(ID) Init; @ end
# Pragma mark-# pragma mark managerdelgate // implementation protocol-(bool) decideframedescription {return no; // controls the framework Description through return YES or NO.} @ end
The final framework completes the change of the corresponding method in the framework based on the description of the Protocol in the delegate. In this example
@implementation MyFrameWork@synthesize delegate,decide;- (NSString *) description{ if([self.decide decideFrameDescription]){ return (@"I am a MyFrameWork"); } else{ return (@"I am a decided MyFrameWork"); }}
Declare the object type accepted by the Protocol in the framework, as shown below:
@ Protocol managerdelegate; // reference to the Protocol declaration @ interface myframework: nsobject {} @ property (nonatomic, assign) nsobject * delegate; // delegate Object Pointer, type: nsobject, that is, all objective-C class parent classes @ property (nonatomic, assign) ID <managerdelegate> decide; // declare that the object that implements the managerdelegate protocol must be accepted-(ID) Init; -(void) calldelegate; @ end
In the end, we implement the managerdelegate protocol in the delegate, and the framework implements changes through the return value of decideframedescription. For example, in the cocoa touch framework, if we want to use a picker (selector), but the framework does not know what we want is the picker of several components and the content of each component, therefore, we need to implement <uipickerviewdelegate> and <uipickerviewdatasource> in our viewcontroler. if 2 is returned in numberofcomponentsinpickerview, The numberofrowsincomponent component selection is completed, and the uipickerviewdatasource protocol is completed.
The running result is as follows:
<This example is for other projects>