Objective-C_语言_协议
来源:互联网 发布:win7如何优化系统 编辑:程序博客网 时间:2024/06/06 20:49
在工程项下个找到ViewController.m文件
#import "ViewController.h"
#import "Student.h"
#import "Walter.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
/*
我们之前讲过非正式协议(NSObject的类目),那么肯定还有正式协议
在OC中,一个类可以实现多个协议,通过协议可以弥补单继承的缺点,但协议跟继承不一样的,协议只是一个方法
列表,方法的实现的靠遵循该协议的类取完成。
协议:协议是一套标准,这个标准里面声明了很多方法,但是不关心具体这些方法是怎么实现的
,具体的实现是由遵循这个协议的类取完成的。
通过协议实现:送外卖的东西,两个类一个学生,送餐员,有一个协议里面有sendfound 忙得话送餐 不忙就不送餐
*/
Student *student=[Student new];
Walter *waiter=[Walter new];
if ([waiter conformsToProtocol:@protocol(FoodProtocol)])
{
NSLog(@"waiter confotms FoodProtocol");
//判断是否遵循这个协议
}
// student.flag=YES;
student.delegate=waiter;
//把对象给他 把遵循协议的waiter赋给student对象给里面的delegate
student.flag=YES;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
#import <Foundation/Foundation.h>
//协议 正式协议
@protocol FoodProtocol <NSObject>
/*
在方法声明时,可以有两个关键字去限制是否必须让循序该协议的类去实现此方法
@required 标注的敌方为必须实现的方法
@optional 标注的方法可以选择实现(可以实现也可以不实现)
*/
//-(void)sendFood:(BOOL)flag;
@required
-(void)sendFood:(BOOL)flag;
@optional
-(void)sayHello;
@end
@interface Student : NSObject
@property (nonatomic,assign)BOOL flag;
@property (nonatomic,assign)id<FoodProtocol> delegate;//声明一个必须实现的对象
//delegate要实现@required里面的对象
@end
Student.m
#import "Student.h"
@implementation Student
//重写设置器
//flag
-(void)setFlag:(BOOL)flag
{
_flag=flag;
//如果代理存在就实现某个方法
//self.delegate代理是否存在
//- (BOOL)conformsToProtocol:(Protocol *)aProtocol;去顶某个方法是否实现了某个协议
/*
self.delegate是否遵循某个协议->confotmsTotocol什么协议->遵循了这个协议就执行sendFood方法
*/
if (self.delegate && [self.delegate conformsToProtocol:@protocol(FoodProtocol)])
{
[self.delegate sendFood:_flag];
}
else
{
NSLog(@"代理不存在");
}
}
@end
===============================================================================Walter.h
#import <Foundation/Foundation.h>
#import "Student.h"
//为什么有导入学生类似为了(遵循协议)这个协议在学生里面
//跟学生达成协议才可以送餐
@interface Walter : NSObject <FoodProtocol>
@end
====================================================================================Walter.m
#import "Walter.h"
@implementation Walter
-(void)sendFood:(BOOL)flag
{
//flag忙于不忙
if (false)
{
NSLog(@"学员忙,我们来送餐");
}
else
{
NSLog(@"学员不忙,我们不送餐");
}
}
@end
- Objective-C_语言_协议
- Objective-C_语言_类目
- Objective-C_语言_延展
- Objective-C_语言_计算机网络
- Objective-C_语言_观察者模式
- Objective-C_语言_单例模式
- objective-C_语言_委托模式
- Objective-C_语言_文件管理
- Objective-C_语言_内存管理2(代码)
- Objective-c语言_协议
- Objective-C_语言 练习题2
- Objective-C_语言_NSNotification(通知)
- Objective-C_继承_初始化方法
- Objective-C_语言_KVO和KVC
- Objective-C_类
- Objective-C_属性
- Objective-C_字面量
- Objective-c语言_复合
- MySQL5.7更改密码时出现ERROR 1054 (42S22): Unknown column 'password' in 'field list'
- 技术人员如何面试
- 数组去除重复
- eclipse启动无响应,停留在Loading workbench状态
- 弹性滑动导航菜单:
- Objective-C_语言_协议
- Java连接SFTP服务器
- learn python(1) print语法
- c语言心得
- YYYYMMDD int型时间转换
- python
- 我的课程总结
- 获取一周前日期
- Apache同一台主机配置多个站点