The role of protocols and the use of protocols
1. The protocol is generally used as a communication between two classes
2. The agreement declares a set of excuses that all classes of objects can be implemented
3. The agreement declares that it is not a class by itself with the @prltocol keyword
4. Two objects, agents and delegates participating in the agreement
5. Proxy, implement a method of the Protocol to implement this Protocol
6. Delegate, use your own method to specify the object to implement the Protocol method (proxy), the agent to implement the corresponding method
[Email protected] The method that must be implemented @optional---the method that can be selected by default @required
Example:
This is a simple proxy callback that contains the reference
Informal agreements
@protocol bcviewdelegate <NSObject>
Parameters
-(void) bcviewbuttondidclicked: (NSString *) text;
@end
Delegate class
@interface Bcview:uiview
Write Property agent
@property (Nonatomic,retain) id<bcviewdelegate>delegate;
@end
@implementation Bcview
-(ID) initWithFrame: (CGRect) frame
{
self = [super Initwithframe:frame];
if (self) {
Initialization code
[Self addallviews];
}
return self;
}
-(void) addallviews
{
UIButton *button = [UIButton Buttonwithtype:uibuttontypesystem];
Button.frame = CGRectMake (100, 100, 100, 40);
Binding a point-and-click event
[Button addtarget:self action: @selector (buttondidclicked:) forcontrolevents:uicontroleventtouchupinside];
[Button settitle:@ "test" forstate:uicontrolstatenormal];
[Self Addsubview:button];
}
-(void) buttondidclicked: (UIButton *) send
{
[Self.delegate bcviewbuttondidclicked:@ "Yang over"];
}
@end
Proxy class:
@interface Bcviewcontroller () <BCViewDelegate>
@property (Nonatomic,retain) Bcview *rootview;
@end
@implementation Bcviewcontroller
-(void) dealloc
{
[_rootview release];
[Super Dealloc];
}
-(void) Loadview
{
Self.rootview = [[Bcview alloc] Initwithframe:[uiscreen mainscreen].bounds];
Self.view = Self.rootview;
[_rootview release];
}
-(void) viewdidload
{
[Super Viewdidload];
Self.rootView.delegate = self;
}
-(void) bcviewbuttondidclicked: (NSString *) text
{
NSLog (@ "%@", text);
NSLog (@ "Agent implementation button click");
}
-(void) didreceivememorywarning
{
[Super didreceivememorywarning];
Dispose of any resources the can be recreated.
if ([self isviewloaded] && Self.view.window = = nil) {
Self.view = nil;
}
}
@end
Two classes between the value, you can use the proxy can also be used (not practical), complex projects, such as the third class to get the return value of the Protocol method, with the agent is more convenient.
The proxy object can be set to itself, you can implement the method of the Protocol in itself
iOS proxy (beginner)