协议Protocol

1、协议:是一组声明方法的集合,不能声明成员变量,作用类似于接口。
          遵守此协议的类就相当于拥有了这个协议的所有方法的声明,如果父类遵守了某个协议,子类也遵守了这个协议。
          遵守这个协议的类可以实现协议中的方法。
关键字:
@required:声明必须遵守的方法
@optional:声明可选的方法
 
2、代理:实现协议的某个方法
3、委托:指定要实现协议方法的对象(代理),代理来实现对应的方法
总结:
委托方:1、定义协议;2、引用代理;3、发送消息
代理方:1、遵守协议;2、实现方法;3、设置自己为代理方
在委托方发送消息:比较可靠的方式
//判断是否有代理方和代理方是否实现了方法
if (self.delegate && [self.delegate respondsToSelector:@selector(popoverListView:dd)])
{
    [self.delegate popoverListView:dd];
}
 
 
补充:(昨天晚上,我遇到一个问题,一直没有解决,于是找自己的笔记,发现自己的笔记,很不全面,很多漏点;看到自己的笔记做成这样,我感到很气愤。回去的时候,我就想,自己一定要把这笔记做详细,不管多简单的,都要做一个完整的记录、注释,不要偷懒!)
时间:2015年07月07日
//—————————————————---------------------委托方--------------------------------------------------
//  BViewController.h
//  星座运程App

#import <UIKit/UIKit.h>
 
@class BViewController;//声明BViewController是一个类,因为在协议中要使用它,但它的定义还在协议的下面,因此就要预声明
//1、定义协议
@protocol BViewControllerDelegate <NSObject>//继承NSObject就可以了
//第一个参数一定是委托方,这样就好区分这个委托是谁的,并且可能还要用到它,这里是BViewController这个类
- (void)returnStarInfo:(BViewController *)Bviewc andMssage:(NSString *)msg andTitle:(NSString *)title;
 
@end
 
@interface BViewController : UIViewController
//2、引用代理
@property(nonatomic,weak)id<BViewControllerDelegate>delegate;
@property(nonatomic,strong)NSDictionary *starDic;
@end
 
//3、发送消息
//  BViewController.m
//  星座运程App
#import "BViewController.h"
//3、在一个适当的时机,发送消息
- (IBAction)returnStarInfo:(UIButton *)sender {
    UIButton *bt=[[UIButton alloc]init];
    bt=sender;
    NSString *str=[self.starDic objectForKey:bt.titleLabel.text];
//当发生了点击绑定动作的按钮时,发送消息
    [self.delegate returnStarInfo:self andMssage:str andTitle:bt.titleLabel.text];
    [self.navigationController popViewControllerAnimated:YES];
}
//————————————————————--------------------------------代理方--------------------------------------------
//  AViewController.m
//  星座运程App
#import "AViewController.h"
#import “BViewController.h”//协议就存在这个文件中中
//1、遵守协议
@interface AViewController ()<BViewControllerDelegate>//协议就存在这个文件中:BViewController.h
 
@end
//2、设置代理
- (IBAction)selectStar:(UIButton *)sender {
    BViewController *bvc=[[BViewController alloc]initWithNibName:@"BViewController" bundle:nil];
    bvc.delegate=self;//设置自己为代理方
    [self.navigationController pushViewController:bvc animated:YES];
}
//实现方法
-(void)returnStarInfo:(BViewController *)Bviewc andMssage:(NSString *)msg andTitle:(NSString *)title{
    self.starInfo.text=msg;
    self.title=[title stringByAppendingString:@" --- 12星座"];
}
//-------------------------------------------------------------------------------------------------------
 
posted @ 2016-04-28 23:04  bonjour520  阅读(382)  评论(0编辑  收藏  举报