Common IOS design modes-delegated mode (IOS development)
The delegation mode has been used in many previous blogs. For example, the UI controls of various complex Cocoa Touch frameworks almost all use delegation to respond to control events or control other objects.
Delegation Mode
-Problem:
All IOS applications are processed in UIApplication, but they are not friendly during the design process. They have a high degree of coupling, unclear responsibilities, and difficult to maintain. Therefore, they need to be constantly reconstructed, therefore, classes that seem to have complex functions need to be divided into classes with specific functions.
In Apple, we often use two types: framework class, various types of use, continuous use, and everything available; Protocol Class and protocol.
The purpose of the Protocol is to reduce the complexity and coupling of an object. Framework classes often generate a pointer to keep objects and send messages to the delegate objects at specific times. Just like our common "obj delegate = self;" delegate object to do something or delegate object control.
-Principle:
// Delegate class PhilosopherDelegate. h @ protocol PhilosopherDelegate
@ Required-(void) sleep;-(void) eat;-(void) work; @ end // ViewController. h @ interface ViewController: UIViewController
@ 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 the reference relationship between the delegate object and the common class.
Although general classes (usually those in the UIViewController class) are provided directly by UIKit, we can implement our own general class Philosopher in this example. I will give the code, but it is really not very important.
// Philosopher. h # import "PhilosopherDelegate. h" @ interface Philosopher: NSObject {...} // you can save the object reference @ property (nonatomic, weak) id
Delegate;-(void) start;-(void) handle; @ end // Philosopher. m # import "Philosopher. h "@ implementation Philosopher @ synthesize delegate;-(void) start {...} -(void) handle {...} @ end
-Specific applications: too many applications, many spaces are delegated, mainly responsible for responding to control events or controlling other objects. For more complex controls such as UITableView, in addition to the delegate protocol, data source protocol must also be implemented. Are specific applications of delegated design patterns.
The delegate method is optional, but the data source method is generally required!