IOS Delegate

宣告

宣告protocol

@required是指採用這個protocol的類別一定要實現這個方法
且預設是指@required

@optional是指採用這個protocol的類別可以選擇性實現這個方法

英文字屬於哪個修飾子

  • @required: a b c d g h
  • @optional: e f
Template.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@class Template;
@protocol TemplateDelegate<NSObject>
//a
//b
@required
-(void)TemplateView:(Template*)templateView WithValueChangeRequired:(float)value;
//c
//d
@optional
-(void)TemplateView:(Template*)templateView WithValueChangeOptional:(float)value;
//e
//f
@required
//g
//h
@end

宣告delegate

宣告這個類別有一個delegate且採用了TemplateDelegate這個protocol

Template.h
1
2
3
@interface Template : UIView
@property (weak)id <TemplateDelegate>delegate;
@end

實作

Template.m
1
2
3
4
5
6
[_delegate TemplateView:self WithValueChangeRequired:1.0f];

if ([_delegate respondsToSelector:@selector(TemplateView:WithValueChangeOptional:)])
{
[_delegate TemplateView:self WithValueChangeOptional:1.0f];
}

套用

Usage.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@interface Usage ()<TemplateDelegate>
{
Template *template;
}
@end

@implementation Usage

- (void)viewDidLoad
{
template.delegate = self;
}

-(void)TemplateView:(Template*)templateView WithValueChangeRequired:(float)value{
// TODO ...
}

// 因為是Optional可以選擇不實作
//-(void)TemplateView:(Template*)templateView WithValueChangeOptional:(float)value{
// // TODO ...
//}
@end