协议的作用以及协议的用法
1.协议一般用作两个类之间的通信
2.协议声明了一组所有类对象都可以实现的借口
3.协议用@prltocol关键字声明 它本身不是类
4.参与协议的两个对象,代理者和委托者
5.代理,实现协议的某个方法,实现这个协议
6.委托,用自己的方法指定要实现协议方法的对象(代理),代理来实现对应的方法
7.@required---必须实现的方法 @optional---可以选择的方法 默认@required
例子:
这是一个简单的代理回调,包含传参
// 非正式协议
@protocol BCViewDelegate <NSObject>
// 参数
- (void)BCViewButtonDidClicked:(NSString *)text;
@end
委托类
@interface BCView : UIView
// 写属性代理                                                    
@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);
    // 绑定点击事件
    [button addTarget:self action:@selector(buttonDidClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    [button setTitle:@"测试" forState:UIControlStateNormal];
    
    [self addSubview:button];
    
}
- (void)buttonDidClicked:(UIButton *)send
{
    [self.delegate BCViewButtonDidClicked:@"杨过"];
    
}
@end
代理类:
@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(@"代理实现button点击");
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if ([self isViewLoaded] && self.view.window == nil) {
        self.view = nil;
    }
}
@end
两个类之间传值,可以用代理也可以不用代理(不实用),复杂的项目中,比如第三个类要得到协议方法的返回值,用代理会比较方便。
可以把代理对象设置为自身,可以在自身中实现协议的方法
原文:http://www.cnblogs.com/bachl/p/4619571.html