iOS通知机制

通知可以告诉多个对象发生了什么事情,一个通知可以被多个对象监听,多个对象发出的多个通知可以被多个人监听

Person.h

1
2
3
4
5
6
7
8
9
#import <Foundation/Foundation.h>

@interface Person : NSObject
/** 姓名 */
@property (strong, nonatomic) NSString *name;

- (void)text;

@end

Person.m

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#import "Person.h"

@implementation Person

- (void)text
{
    NSLog(@"text ---- %@", self.name);
}

- (void)dealloc
{
// 需要在人对象死时去掉观察者
[[NSNotificationCenter defaultCenter] removeObserver:self];
}


@end

viewController

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
#import "ViewController.h"
#import "Person.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 1.什么是通知
    
    // 3个对象
    Person *p1 = [[Person alloc] init];
    p1.name = @"p1";
    Person *p2 = [[Person alloc] init];
    p2.name = @"p2";
    Person *p3 = [[Person alloc] init];
    p3.name = @"p3";
    
    // 首先拿到通知中心添加观察者
    [[NSNotificationCenter defaultCenter] addObserver:p1 selector:@selector(text) name:@"TextNofication" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:p2 selector:@selector(text) name:@"TextNofication" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:p3 selector:@selector(text) name:@"TextNofication" object:nil];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"TextNofication" object:@"123"];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"TextNofication" object:@"345"];
}

@end

不同对象发送了TextNofication消息,所有的观察者全部都会执行text方法,因此一共有六次执行

1
2
3
4
5
6
2015-12-25 12:06:16.588 test[1180:88758] text ---- p1
2015-12-25 12:06:16.588 test[1180:88758] text ---- p2
2015-12-25 12:06:16.588 test[1180:88758] text ---- p3
2015-12-25 12:06:16.588 test[1180:88758] text ---- p1
2015-12-25 12:06:16.588 test[1180:88758] text ---- p2
2015-12-25 12:06:16.588 test[1180:88758] text ---- p3

这里一共要注意两点:

  1. 发出通知跟接受通知是在一个线程中完成的,你再哪个线程发出通知,就在该线程调用接受通知要调用的方法。
  2. 谁成为了通知的观察者,需要在它死掉时卸任。
1
2
3
4
5
- (void)dealloc
{
// 需要在人对象死时去掉观察者
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
文章作者: Ammar
文章链接: http://lizhaoloveit.cn/2014/05/11/iOS%E9%80%9A%E7%9F%A5%E6%9C%BA%E5%88%B6/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Ammar's Blog
打赏
  • 微信
  • 支付宝

评论