日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

IOS之学习笔记十四(协议的定义和实现)

發布時間:2023/12/4 编程问答 20 豆豆
生活随笔 收集整理的這篇文章主要介紹了 IOS之学习笔记十四(协议的定义和实现) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1、正式協議的定義

@protocol 協議名 <父協議1, 父協議2>{零個到多個方法定義}

一個協議可以有多個直接父協議,但協議只能繼承協議,不能繼承類

協議只有方法簽名,沒有方法實現

?

?

?

?

?

?

?

?

2、實現協議

@interface 類名 : 父類 <協議1,協議2…>@end

?

協議和java里面的接口差不多

?

如果要使用協議定義變量,有如下兩種語法

NSObject<協議1,協議2>*變量;

id<協議1,協議2> 變量;

?

@optional關鍵字之后聲明的方法可選實現

@required關鍵字之后聲明的方法必選實現

?

?

?

?


3、測試Demo

1)、FirstProtocol.h

#ifndef FirstProtocol_h #define FirstProtocol_h@protocol FirstProtocol -(void)first; @end#endif /* FirstProtocol_h */

?

?

?

2)、SecondProtocol.h

#ifndef SecondProtocol_h #define SecondProtocol_h @protocol SecondProtocol -(void)second; @end#endif /* SecondProtocol_h */

?

?

3)、ThirdProtocol.h

#import "FirstProtocol.h" #import "SecondProtocol.h"#ifndef ThirdProtocol_h #define ThirdProtocol_h @protocol ThirdProtocol <FirstProtocol, SecondProtocol> -(void)third; @end#endif /* ThirdProtocol_h */

?

?

?

4)、DoProtocol.h

#import <Foundation/Foundation.h> #import "ThirdProtocol.h"#ifndef DoProtocol_h #define DoProtocol_h @interface DoProtocol : NSObject <ThirdProtocol> @end#endif /* DoProtocol_h */

?

?

?

?

5)、DoProtocol.m

#import <Foundation/Foundation.h>#import "DoProtocol.h"@implementation DoProtocol -(void)first {NSLog(@"this first method"); } -(void)second {NSLog(@"this second method"); } -(void)third {NSLog(@"this third method"); } @end

?

?

?

6)、main.m

#import "DoProtocol.h" #import "ThirdProtocol.h" #import "FirstProtocol.h"int main(int argc, char * argv[]) {@autoreleasepool {DoProtocol *protocal = [DoProtocol new];[protocal first];[protocal second];[protocal third];NSObject<FirstProtocol> *first = [[DoProtocol alloc] init];[first first];id<SecondProtocol> second = [[DoProtocol alloc] init];[second second];} }

?

?

?


4、運行結果

this first method this second method this third method this first method this second method

?

?

?

總結

以上是生活随笔為你收集整理的IOS之学习笔记十四(协议的定义和实现)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。