The delegate model is used in many of the previous blogs, such as the various complex cocoa touch framework UI controls, which almost all use delegates to respond to control events or to control other objects.
Delegate mode
Problem
Handling all iOS apps is done in UIApplication, but in the design process is not friendly, it is high-quality, the responsibility is unclear, difficult to maintain, the need for continuous reconstruction, it is necessary to the seemingly complex class decomposition or dispatch success can be clearly defined classes.
Apple we often use two kinds, one is the framework class, all kinds of use, continuous use, anything can be used, and the other is the Protocol class, is the protocol.
The purpose of the agreement, after all, is to reduce the complexity of an object and the Lotus degree of goodness. The framework class often generates a pointer to hold the object and sends a message to the delegate object at a specific point in time. Just like our common "obj delegate = self;" Delegate object to do something or delegate object control.
Principle
Delegate class Philosopherdelegate.h@protocol Philosopherdelegate <NSObject> @required-(void) sleep;-(void) eat;-(void) Work, @end//Viewcontroller.h@interface viewcontroller:uiviewcontroller<philosopherdelegate> @end// Viewcontroller.m@implementation viewcontroller-(void) viewdidload{ [Super Viewdidload]; Philosopher *obj = [[Philosopher alloc] init]; Obj.delegate = self; [obj start];} #pragma--Philosoperdelegate method implementation-(void) sleep{ NSLog (@ "sleep ...");} -(void) eat{ NSLog (@ "Eat ..."); -(void) work{ NSLog (@ "work ..."); @end
Note that the obj.delegate = Self statement in the Viewdidload method specifies a reference relationship for the delegate object and the generic class.
Although general-purpose classes (usually Uiviewcontroller and the like) are provided directly by Uikit, but in this case we have to implement our own generic class philosopher, I give the code, but really is not very important part.
Philosopher.h#import "PhilosopherDelegate.h" @interface philosopher:nsobject{... } You can save references to Objects @property (nonatomic, weak) id<philosopherdelegate> delegate;-(void) start;-(void) handle; @end// Philosopher.m#import "Philosopher.h" @implementation philosopher@synthesize delegate;-(void) start{ ...} -(void) handle{ ...} @end
-Specific application: Too many, many spaces have delegates, primarily responsible for responding to control events or controlling other objects. For more complex controls, such as UITableView, you need to implement a data source protocol in addition to implementing a delegation protocol. Are the specific applications of the commissioned design pattern.
The delegate method is optional, but the method of the data source is generally necessary!
iOS common design mode-delegate mode (iOS development)