6.協議也能遵守(繼承)協議main.m
1 //
2 // main.m
3 // Protocol
4 //
5 // Created by sixleaves on 15/5/13.
6 // Copyright (c) 2015年 itcast. All rights reserved.
7 //
8 9 #import <Foundation/Foundation.h>
10 #import "Person.h"
11 #import "Dog.h"
12 #import "WPProtocol.h"
13 int main(
int argc,
const char * argv[]) {
14 /*
15 Dog沒有遵守WPProtocol協議,
16 Person遵守了WPProtocol協議,
17 WPProtocol又遵守GHProtocol協議
18 */19 20 Person *p = [[Person alloc] init];
21 22 [p test1];
23 24 25 Person<GHProtocol> *p2 = [[Person alloc] init];
26 [p2 love];
27 28 // Dog對象沒遵守WPProtocol,所以會有警告。
29 Dog<WPProtocol> *d = [[Dog alloc] init];
30 31 32 return 0;
33 }
34 /*
35 1.protocol的作用(什么是協議、用途):
36 用來聲明一大堆的方法。
37
38 2.協議的語法:
39
40 @protocol WPProtocol <NSObject>
41 
42 @end
43 遵守協議的語法:<協議名>
44 采用多協議語法:<協議1, 協議2,
>
45
46 3.基協議:
47 NSObject是一個基協議和基類同名,幾乎所有的OC協議都要遵守NSObject協議。
48 基協議聲明了很多常用的接口。所以自己寫得protocol最好也要遵守基協議。
49
50 4.限制對象類型
51 限制變量只能保存遵守某個、某些協議的對象
52 如果不遵守會有警告。
53
54 5.協議前置聲明(@protocol 協議名;)
55 與類的前置聲明的原因一樣,在.h文件中僅僅需要知道是個協議就行,所以可用前置聲明
56 在.m文件中,需要知道其內部構造,再導入。
6.協議也能遵守(繼承)協議
57 */ WPProtocol.h
1 //
2 // WPProtocol.h
3 // Protocol
4 //
5 // Created by sixleaves on 15/5/13.
6 // Copyright (c) 2015年 itcast. All rights reserved.
7 //
8
9 #import <Foundation/Foundation.h>
10 #import "GHProtocol.h"
11 @protocol WPProtocol <NSObject, GHProtocol>
12
13 - (void)test1;
14 @required
15 - (void)test2;
16 - (void)test3;
17 - (void)test4;
18 @optional
19 - (void)test5;
20
21 @end
22