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