通知可以告诉多个对象发生了什么事情,一个通知可以被多个对象监听,多个对象发出的多个通知可以被多个人监听
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]; 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 3 4 5
| - (void)dealloc { // 需要在人对象死时去掉观察者 [[NSNotificationCenter defaultCenter] removeObserver:self]; }
|