IOS之学习笔记十四(协议的定义和实现)
生活随笔
收集整理的這篇文章主要介紹了
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之学习笔记十四(协议的定义和实现)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: IOS学习笔记之十一(包装类、descr
- 下一篇: IOS之学习笔记十五(协议和委托的使用)