zoukankan      html  css  js  c++  java
  • Objective-C 【protocol 的引用问题】

    首先,这里发表声明:

    本博客从今天起从博客园落脚,从前在CSDN写的全部博客已经转载于此,希望有越来越多的人能看到我的博客,并在评论中交流学习经验。

    好了,废话不多说,进入正题。

    ———————————————————————————————————————————
    protocol的引用问题

    这一部分是对前面我们学习过的协议 protocol的补充,所以知识涉及的比较少,但是也很重要,希望大家也要熟练掌握:

    直接上代码:


    main.m

    #import <Foundation/Foundation.h>
    #import "Student.h"
    #import "workProtocol.h"
    //★注意,虽然Student类遵守这个协议,但是我们还要在main.m中导入这个协议的头文件(因为在Student类的头文件中我们用的是引入协议(@protocol ......)我们只是让系统知道有Student这个类,只是通过了编译而已)
    int main(int argc, const char * argv[]) {
        @autoreleasepool {
            Student *stu=[Student new];
            
            [stu run];
            
            [stu work];
        }
        return 0;
    }

    workProtocol.h

    #import <Foundation/Foundation.h>

    @protocol workProtocol <NSObject>
    -(void)work;
    @end

    Student.h

    #import <Foundation/Foundation.h>
    @protocol workProtocol;//我们不用每次编译的时候都编译一次这个协议,我们只需要在运行的时候编译一次就够了,所以我们这里可以只是告诉编译器一声 workProtocol是一个协议 就好了。(其目的还是为了节约编译的内存和时间)

    //而且我们还可以在一个类的.h文件中直接去写一个协议,这样可以直接用这个协议(work2)
    @protocol work2 <NSObject>
    -(void)run;
    @end

    @interface Student : NSObject <workProtocol,work2>

    @end

    Student.m

    #import "Student.h"
    #import "workProtocol.h"
    //我们只需在.m中用到协议中的方法的时候再用import导入即可
    @implementation Student
    -(void)work
    {
        NSLog(@"student work!");
    }

    -(void)run
    {
        NSLog(@"run!");
    }
    @end


    ———————————————————————————————————————————

  • 相关阅读:
    G面经prepare: Maximum Subsequence in Another String's Order
    G面经prepare: Set Intersection && Set Difference
    G面经prepare: Pattern Match
    G面经prepare: Data Stream Average
    Summary: Final Keyword
    G面经prepare: Android Phone Unlock Pattern
    G面经prepare: Jump Game Return to Original Place
    G面经prepare: Reorder String to make duplicates not consecutive
    G面经prepare: Sort String Based On Another
    G面经Prepare: Valid Preorder traversal serialized String
  • 原文地址:https://www.cnblogs.com/wzy294250051/p/4795717.html
Copyright © 2011-2022 走看看