OC Protocol 協議

1、概述

  • 協議就是委託(delegate)/代理,是指一個對象提供機會對另外一個對象的變化作出反應或者影響另外一個對象的行爲。
  • 協議只能一個用途,就是爲繼承的類,聲明出一堆方法的聲明。
  • 基類遵照的協議,其派生類也要遵照其基類遵照的協議,也就是說父類的協議能夠被子類繼承。
  • 在OC中類不能多重繼承,只能單繼承,而協議卻能夠多繼承。
  • 協議聲明的方法能夠由繼承的任意類去實現。
  • 協議 <NSObject> 是一切協議的基協議。
  • 協議能夠遵照協議,也就是說一個協議能夠去遵照(繼承)其它協議,這樣就能夠擁有其它協議的全部方法的聲明。
  • 在協議中還有兩個關鍵字@optional and @required,@optional 修改的方法聲明告訴開發者能夠這個方法能夠實現,也能夠不實現。@required修飾的方法聲明告訴開發都這個方法必須實現,固然,這兩個關鍵字修改的方法,均可以不去理會,但xcode會給出警告。

2、協議定義格式

1 // 定義的協議名稱 遵照協議名稱
2 @protocol MyProtocol <NSObject>
3 @required
4 
5 @optional
6 
7 @end

 

3、例子

 1 // 委託者 DemoViewController.h
 2 #import <UIKit/UIKit.h>
 3 
 4 @protocol DemoDelegate <NSObject>
 5 - (void)setEditWithValue:(NSString *)aValue;
 6 @end
 7 
 8 @interface DemoViewController : UIViewController
 9 {
10     id<DemoDelegate> iDelegate;
11 }
12 
13 // 此delegate就是setDelegate方法
14 @property (nonatomic, assign) id<DemoDelegate> iDelegate;
15 
16 @end
17 
18 // DemoViewController.m
19 #import "DemoViewController.h"
20 
21 @interface DemoViewController ()
22 {
23     NSString *iVarString;
24 }
25 
26 @property (nonatomic, copy) NSString *iVarString;
27 
28 - (void)print;
29 
30 @end
31 
32 @implementation DemoViewController
33 @synthesize iDelegate;
34 @synthesize iVarString;
35 
36 - (void)print
37 {
38     [self.iDelegate setEditWithValue:@"test"];
39 }
40 
41 @end
42 
43 
44 // 被委託者,要注意,在被委託中要設置代碼理對象
45 // DemoController.h
46 #import <Foundation/Foundation.h>
47 
48 #import "DemoViewController.h"
49 
50 @interface DemoController : NSObject <DemoDelegate>
51 
52 @end
53 
54 // DemoController.m
55 #import "DemoController.h"
56 
57 @interface DemoController ()
58 {
59     DemoViewController *iDVController;
60 }
61 
62 @property (nonatomic, retain) DemoViewController *iDVController;
63 
64 - (instancetype)initWithValue:(NSString *)aValue;
65 
66 @end
67 
68 @implementation DemoController
69 @synthesize iDVController;
70 
71 - (instancetype)initWithValue:(NSString *)aValue
72 {
73     if (self = [super init])
74     {
75         self.iDVController = [[DemoViewController alloc] init];
76         [self.iDVController setIDelegate:self];
77     }
78     
79     return self;
80 }
81 
82 - (void)setEditWithValue:(NSString *)aValue
83 {
84     // to do
85     NSLog(@"detail page edit value: %@", aValue);
86 }
87 
88 @end

PS: 在被委託中設置的代理對象,就是委託都的成員屬性,即:@property delegate的getter and setter方法。 xcode

1 @interface DemoViewController
2 {
3   id<DemoController> iDelegate;  
4 }
5 
6 @property (nonatomic, assign) id<DemoController> iDelegate;
相關文章
相關標籤/搜索