您的位置:首页 > 其它

协议(Protocol)---实例

2016-03-02 18:58 141 查看
协议:声明一些必须实现的方法和选择实现的方法,用来声明一些方法,即一个Protocol是由一系列的方法声明组成的。

建立协议文件步骤:将鼠标放到文件列表处,利用快捷键 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;
}


运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: