通知机制(初学者必须知道的设计模式)

通知是一种设计模式,与代理有类似的地方,一般实现分为几个步骤

1、设置监听

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(recive: ) name:@”notification” object:nil];

2、发送通知

NSDictionary *dic = [NSDictionary dictionaryWithObject:@”value” forKey:@”key”];

[[NSNotificationCenter defaultCenter] postNotificationName:@”notification” object:nil userInfo:dic];

3、通知响应

– (void)recive:(NSDictionary *)userInfo
{
NSLog(@”%@”, userInfo);
}

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
@implementation SAViewController
 
-(id)init
{
    if (self = [super init]){
        self.view.backgroundColor = [UIColor whiteColor];
 
        // 1、设置监听
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(recive:) name:@"notification" object:nil];
 
        // 创建一个按钮,当按钮点击时触发通知发送事件
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.frame = CGRectMake(10, 50, 50, 30);
        [button setTitle:@"abc" forState:UIControlStateNormal];
        [self.view addSubview:button];
        [button addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return self;
}
 
- (void)buttonClick
{
 
    // 2、发送通知
    NSDictionary *dic = [NSDictionary dictionaryWithObject:@"value" forKey:@"key"];
 
    [[NSNotificationCenter defaultCenter] postNotificationName:@"notification" object:nil userInfo:dic];
 
}
 
// 3、通知响应
- (void)recive:(NSDictionary *)userInfo
{
    NSLog(@"%@", userInfo);
}
@end

PS:这种设计模式一般在控制器与控制器之间数据交互场景下使用,通知的发送者与接收者一般都不是同一个控制器,否则直接调方法不就行了吗?

Leave a Reply