协议(Protocol)---实例
2016-03-02 18:58
141 查看
协议:声明一些必须实现的方法和选择实现的方法,用来声明一些方法,即一个Protocol是由一系列的方法声明组成的。
建立协议文件步骤:将鼠标放到文件列表处,利用快捷键 command +N 健,得到如图
lamcoProtocol.h 文件
lamcoProtocol.h 文件
Student.h文件
Student.m 文件
OtherStudent.h文件
OtherStudent.m 文件
main.m文件
运行结果:
建立协议文件步骤:将鼠标放到文件列表处,利用快捷键 command +N 健,得到如图
lamcoProtocol.h 文件
#import <Foundation/Foundation.h> @protocol lamcoProtocol <NSObject> @required // 必须实现的方法 -(void)study; @optional // 可实现哥不实现的方法 -(void)work; @end
lamcoProtocol.h 文件
#import <Foundation/Foundation.h> @protocol bankProtocol <NSObject> -(void)giveme; @end
Student.h文件
#import <Foundation/Foundation.h> #import "lamcoProtocol.h" #import "bankProtocol.h" @interface Student : NSObject<lamcoProtocol,bankProtocol> @end
Student.m 文件
#import "Student.h" @implementation Student -(void)study { NSLog(@"每天按时上课,复习,预习!"); } -(void)work { NSLog(@"保证给你安排一个技术岗位"); } -(void)giveme { NSLog(@"每月按时还款"); } @end
OtherStudent.h文件
#import <Foundation/Foundation.h> @interface OtherStudent : NSObject @end
OtherStudent.m 文件
#import "OtherStudent.h" @implementation OtherStudent @end
main.m文件
#import <Foundation/Foundation.h> #import "Student.h" #import "OtherStudent.h" int main(int argc, const char * argv[]) { @autoreleasepool { Student *stu=[Student new]; // 判断是否有蓝科协议 if ([stu conformsToProtocol:@protocol(lamcoProtocol)]) { // 判断协议是否有该方法 if ([stu respondsToSelector:@selector(study)]) { [stu study]; [stu work]; }else{ NSLog(@"找不到好工作"); } } else{ NSLog(@"没有参加培训"); } if ([stu conformsToProtocol:@protocol(bankProtocol)]) { if ([stu respondsToSelector:@selector(giveme)]) { [stu giveme]; } else{ NSLog(@"没有信誉可言"); } }else{ NSLog(@"不能参加iOS培训"); } OtherStudent *other=[OtherStudent new]; if ([other conformsToProtocol:@protocol(lamcoProtocol)]){ if ([other respondsToSelector:@selector(study)]) { NSLog(@"欢迎来到蓝科"); } else{ NSLog(@"不愿参加培训"); } } } return 0; }
运行结果:
相关文章推荐
- Oracle知识点
- Unity3D与android交互---构建android插件
- 寻找屏幕上的点击位置--Queen核心技术分享
- 深刻的理解递归汉诺塔(Hanoi)
- codeforces--623C The Smallest String Concatenation
- ORA-00257: archiver error --11GR2 RAC 设置归档路径和开启flashback
- 15年蓝桥杯第7题
- 替换空格
- C语言数组
- SPOJ LCS(后缀自动机)
- ZOJ 3603 Draw Something Cheat(模拟)
- 友元成员函数
- java并发编程 Lock
- [异常] Android - Your project contains errors,please fix them before running your application
- ORA-01157: cannot identify/lock data file %s - see DBWR trace file的处理
- 杭电2095
- 构建之法
- P98 图 两色染色
- java并发编程 Lock
- SPRING IN ACTION 第4版笔记-第三章ADVANCING WIRING-006-给bean运行时注入值(Environment,Property文件)