The cocoa touch framework uses a large number of delegation. According to Apple's documents, delegate is a form of delegation mode adopted by the cocoa touch framework. Instance code download Portal
Understanding delegation and necessary preparation
(1) Agreement
The objective-C protocol is similar to the abstract class of C ++ and the Java interface. Its definition is as follows:
@protocol MyButtonDelegate <NSObject>@optional- (void) didPressButton;@end
@ Protocol is the protocol keyword, mybuttondelegate is the protocol name, And didpressbutton is the method in the Protocol.
(2) ID type
The ID type can be understood as a pointer to any object,
It is defined:
typedef struct objc_class *Class;typedef struct objc_object { Class isa;} *id;
(3) Adapter Mode
In the design mode, there is no delegate mode. But there is an adapter mode, the adapter mode can be understood as this, if we went to Hong Kong, to connect my computer to power, we found that some plug boards can not be plugged in (Hong Kong uses a British plug ), you can only insert one converter to connect the computer to the converter. This is the adapter mode in life. Most delegate modes are the functions of object adapters implemented,
(4) Instances
We want to implement a self-built component similar to the uibutton function. First, we inherited mybutton from uiview. At this time, we encountered a problem. We don't know who will use mybutton in the future, but we know that every button that uses mybutton needs to be pressed, get a message to inform the adaptee object that uses mybutton, and mybuttton is pressed.
At this time, our adaptation <target> is as follows:
@protocol MyButtonDelegate <NSObject>@optional- (void) didPressButton;@end
My adapter is mybutton, which uses
@property (nonatomic,assign) id <MyButtonDelegate>delegate;
if (delegate && [delegate respondsToSelector:@selector(didPressButton)]) { [delegate performSelector:@selector(didPressButton)]; }
Adaptee can be any object. In this example, It is rootviewcontroller (which implements the <mybuttondelegate> protocol)
(5) in-depth understanding of delegation Mode
The implementation of the delegate mode can also be implemented through block, but it is only suitable for code that is executed in one-time callback.