NSNotificationCenter观察者模式
来源:互联网 发布:python 书籍推荐 编辑:程序博客网 时间:2024/06/08 06:55
NSNotificationCenter实现了观察者模式,允许应用的不同对象间以松耦合的方式进行通信。
NSNotificationCenter相当于一个消息中心,首先由Observer组件向NSNotificationCenter进行注册—表明该Observer组件对哪些NSNotification感兴趣。
当Poster向NSNotificationCenter发送NSNotification之后,所有在NSNotificationCenter上注册过的、对该NSNotification感兴趣的Observer对会被激发。
NSNotification代表Poster与Observer之间的信息载体,该对象包含如下只读属性。
@property (readonly, copy) NSString *name;
通知的名字@property (nullable, readonly, retain) id object;
通知的Poster@property (nullable, readonly, copy) NSDictionary *userInfo;
用于携带通知的附加信息
发送通知:
- (void)postNotification:(NSNotification *)notification;
- (void)postNotificationName:(NSString *)aName object:(nullable id)anObject;
- (void)postNotificationName:(NSString *)aName object:(nullable id)anObject userInfo:(nullable NSDictionary *)aUserInfo;
注册通知:
- (void)addObserver:(id)observer selector:(SEL)aSelector name:(nullable NSString *)aName object:(nullable id)anObject;
- (id <NSObject>)addObserverForName:(nullable NSString *)name object:(nullable id)obj queue:(nullable NSOperationQueue *)queue usingBlock:(void (^)(NSNotification *note))block
使用NSNotificationCenter除了可以监听系统组件发出的通知(系统已经命名好名称)之外,也可以监听程序自己发出的通知(通知名称由自己命名)。
监听系统组件发出的通知:
- (void)viewDidLoad { [super viewDidLoad]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(finishLaunching) name:UIApplicationDidFinishLaunchingNotification object:[UIApplication sharedApplication]];}-(void)finishLaunching{ NSLog(@"finishLaunching");}
监听自定义通知:
- (void)viewDidLoad { [super viewDidLoad]; UIButton* poster=[[UIButton alloc] initWithFrame:CGRectMake(100, 100, 100, 100)]; poster.backgroundColor=[UIColor redColor]; [self.view addSubview:poster]; [poster addTarget:self action:@selector(post) forControlEvents:UIControlEventTouchUpInside]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(whenClick:) name:@"click" object:nil];}-(void)post{ NSNotification* notication=[[NSNotification alloc] initWithName:@"click" object:nil userInfo:@{@"name":@"ricky"}]; [[NSNotificationCenter defaultCenter] postNotification:notication];}-(void)whenClick:(NSNotification*)notificaton{ NSLog(@"name=%@",[notificaton.userInfo objectForKey:@"name"]);}
- 设计模式 观察者 NSNotificationCenter
- NSNotificationCenter观察者模式
- NSNotificationCenter(观察者模式) 的使用
- NSNotificationCenter 观察者
- 【IPhone开发】NSNotificationCenter观察者模式给主线程发送通知
- IOS通知中心(观察者模式)[NSNotificationCenter defaultCenter]
- NSNotificationCenter模式
- 消息中心和观察者:NSNotificationCenter
- NSNotificationCenter的设计模式
- NSNotificationCenter 与设计模式 (Observer)
- NSNotificationCenter 与设计模式 (Observer)
- 观察者模式
- 观察者模式
- 观察者模式
- 观察者模式
- 观察者模式
- 观察者模式
- 观察者模式
- 开发iOS应用要比开发安卓应用省时约30%
- Leetcode138: Partition List
- Leetcode sql算法题
- 简单邻接表构造图
- hdu1219
- NSNotificationCenter观察者模式
- QQ space
- mysql命令操作
- leetcode-Same Tree
- atomic 加锁操作
- XMPP 及时通信二
- POJ Unimodal Palindromic Decompositions(DP)
- 表的两种连接方式
- Palindrome Partitioning I,II(DFS,DP)