Objective-C 【protocol 的引用問題】,objectivecprotocol

來源:互聯網
上載者:User

Objective-C 【protocol 的引用問題】,objectivecprotocol

———————————————————————————————————————————
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


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

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.