zoukankan      html  css  js  c++  java
  • 协议(Protocol)---实例

    协议:声明一些必须实现的方法和选择实现的方法,用来声明一些方法,即一个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;
    }

     运行结果:

  • 相关阅读:
    数据库的创建与管理
    html+css画虚线,实线
    隐藏导航练习
    表单—注册邮箱
    整理—运算符l
    softmax函数理解
    离线配置Anaconda3+tensorflow-gpu1.4.0+cuda8.0+cudnn6.0
    stl总结精简版
    hdu_2030
    康托展开
  • 原文地址:https://www.cnblogs.com/bolin-123/p/5236137.html
Copyright © 2011-2022 走看看