6.協(xié)議也能遵守(繼承)協(xié)議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協(xié)議,
16 Person遵守了WPProtocol協(xié)議,
17 WPProtocol又遵守GHProtocol協(xié)議
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對(duì)象沒遵守WPProtocol,所以會(huì)有警告。
29 Dog<WPProtocol> *d = [[Dog alloc] init];
30 31 32 return 0;
33 }
34 /*
35 1.protocol的作用(什么是協(xié)議、用途):
36 用來聲明一大堆的方法。
37
38 2.協(xié)議的語法:
39
40 @protocol WPProtocol <NSObject>
41 
42 @end
43 遵守協(xié)議的語法:<協(xié)議名>
44 采用多協(xié)議語法:<協(xié)議1, 協(xié)議2,
>
45
46 3.基協(xié)議:
47 NSObject是一個(gè)基協(xié)議和基類同名,幾乎所有的OC協(xié)議都要遵守NSObject協(xié)議。
48 基協(xié)議聲明了很多常用的接口。所以自己寫得protocol最好也要遵守基協(xié)議。
49
50 4.限制對(duì)象類型
51 限制變量只能保存遵守某個(gè)、某些協(xié)議的對(duì)象
52 如果不遵守會(huì)有警告。
53
54 5.協(xié)議前置聲明(@protocol 協(xié)議名;)
55 與類的前置聲明的原因一樣,在.h文件中僅僅需要知道是個(gè)協(xié)議就行,所以可用前置聲明
56 在.m文件中,需要知道其內(nèi)部構(gòu)造,再導(dǎo)入。
6.協(xié)議也能遵守(繼承)協(xié)議
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