协议 Protocol 的使用

#import <Foundation/Foundation.h>

/*
 协议的的语法
 @protocol 协议的名称
 //方法列表
 @end
 
 @protocol <#protocol name#> <NSObject>
 
 <#methods#>
 
 @end
 */

//协议  正式协议用 @protocol 来定义
@protocol FoodProtocol <NSObject>

/*
 在方法声明时,可以有两个关键字去限制是否必须让循序该协议的类去实现此方法。
 @required  标注的地方为必须实现的方法
 @optional  标注的方法可以选择实现
 */
@required
-(void)sendFood:(BOOL)flag;

@optional
-(void)sayHello;
@end

@interface Student : NSObject

@property (nonatomic,assign)BOOL flag;

//声明一个必须实现协议的对象
@property (nonatomic,assign) id<FoodProtocol>delegate;

@end


#import "Student.h"

@implementation Student

//flag的设置器
-(void)setFlag:(BOOL)flag
{
    _flag = flag ;
    
    //- (BOOL)conformsToProtocol:(Protocol *)aProtocol;  //确定一个对象是否实现了某个协议
    
    if (self.delegate && [self.delegate conformsToProtocol:@protocol(FoodProtocol)])
    {
        [self.delegate sendFood:_flag];
    }
    else
    {
        NSLog(@"代理不存在");
    }

}
@end

#import <Foundation/Foundation.h>
#import "Student.h"  //注意导入头文件
/*
 实现协议
 语法:
 @interface <#class name#> : 父类名<协议1,协议2>
 
 @end
 
 @interface <#class name#> : <#superclass#>
 
 @end
 
 
 */
//类实现协议方法
@interface Waiter : NSObject<FoodProtocol>

@end

#import "Waiter.h"

@implementation Waiter

//实现协议的方法
-(void)sendFood:(BOOL)flag
{
    if (flag)
    {
        NSLog(@"学员忙,我们送餐");
    }
    else
    {
        NSLog(@"学员不忙,我们不送餐");
    }
}

@end


#import "ViewController.h"
#import "Student.h"
#import "Waiter.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
Student *student = [Student new];
    Waiter *waiter = [Waiter new];
    
    
    //判断是否遵循协议
//    if ( [waiter conformsToProtocol:@protocol(FoodProtocol)])
//    {
//        NSLog(@"waiter conforms FoodProtocol");
//    }
    
    student.delegate = waiter;
    student.flag = YES;
    
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

打印结果:

2015-12-21 17:54:06.485 OC_09_02[2354:168785] 学员忙,我们送餐

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值