MZN's understanding of iOS (1) -- personal understanding of proxy delegate, mzndelegate
After one year of iOS, I want to record my understanding of the knowledge point.
Original: http://www.cnblogs.com/A--G/p/4900241.html reproduced please note
Article 1: record the understanding of the delegate (delegate, also called proxy) in iOS.
Therefore, delegate is the meaning of proxy. it is inconvenient for one thing to do, and then it is handed over to others for implementation, such as Class A and Class B, an object of A has a task aTask to be implemented in Class B, because although A event is triggered by Class A, it cannot be implemented in Class A itself, therefore, if you want to give B the help, A and B agree on an agreement:
In Class:
@ Protocol ADelegate <NSObject>
-(Void) aTask;
@ End
// Proxy attribute, which specifies that the ADelegate protocol must be implemented for the proxy object
@ Property (nonatomic, retain) id <ADelegate> aDelegate;
Class B:
In Class B, Class B inherits the proxy of Class A and agrees to the Agreement. In the future, we will proceed as we have said:
// Inherit A's proxy Protocol
@ Interface B () <ADelegate>
@ End
A uses an event, such as clicking A button, to trigger A task in onBButtonClicked:
// Click the button
-(Void) onBButtonClicked {
// In Class B, initialize A Class A Object aObj = [[A alloc] init];
AViewController * aObj = [[AViewController alloc] init];
// Specify the proxy of Class A. This is done by aObj.
AObj. aDelegate = self;
// Determine whether the _ aDelegate instance has implemented the aTask Method
// Avoid listening for A classes that do not implement aDelegate.
If ([A. aDelegate respondsToSelector: @ selector (aTask)]) {
// _ ViewDelegate object call the agent method to trigger the task
[A. aDelegate aTask];
NSLog (@ "excute A's aTask ");
}
}
// Implement the task of B in the proxy method
-(Void) aTask {
// Task content
NSLog (@ "aTask is execute .");
}
Demo URL: DelegateDemo.zip
Supplement: 1. In Protocol @ Protocol, some methods may not always need to be implemented. You can add some keywords as needed to mark the importance of the method, such
@ Required // required method @ optional // optional method
2. protocols can be extended from another protocol, and aDelegate can be extended from NSObject;
3. attributes and member variables cannot be defined in the Protocol. methods can only be defined;
Introduction:
In fact, in ObjC, the protocol is used to constrain a class to implement certain methods. From the object-oriented perspective, this class and the interface do not necessarily have a natural relationship,
It may be two things in a completely different sense. This pattern is called a proxy pattern (Delegation ). This mode is widely used in the Cocoa framework to separate data from the UI,
Basically, all protocols end with Delegate.
Reference: http://blog.csdn.net/jianxin160/article/details/47753189