设计模式 观察者 NSNotificationCenter

来源:互联网 发布:ubuntu鼠标指针主题 编辑:程序博客网 时间:2024/05/29 11:32

默认的广播站,类似 NSUserDefault 的共享实例

NSNotificationCenter *center = [NSNotificationCenter defaultCenter];

注册观察者,开始收听广播,此处代码一般放在 viewWillAppear 中,并在 viewWillDisappear 中停止监听

[center addObserver:(id)observer    // 收听广播的观察者,控制器是最常见的观察者,所以此参数通常为self           selector:(SEL)@selector(execute:)  // 处理广播的方法,收到名为name的广播后调用此方法               name:(NSString *)name  // 广播名称             object:(id)sender        // 指定收听特定的对象发出的广播,通常nil,表示收听所有发送者的广播


实现响应广播的方法

- (void)execute:(NSNotification *)notification {    notification.name       // 广播站名称,对应注册时的 name 参数    notification.object     // 发送此通知的对象,对应注册时的 sender 参数    notification.userInfo   // 广播传递的信息,取决于广播的类型        if(notification.object && [notification.object isKindOfClass:[Test class]]){        //do something    }}



结束收听,关掉广播

 [[NSNotificationCenter defaultCenter] removeObserver:self];  // 在离开堆前被调用,可以在这里关闭广播 -(void) dealloc{     [[NSNotificationCenter defaultCenter] removeObserver:self]; }



发出广播,即通知相应的观察者

[[NSNotificationCenter defaultCenter] postNotificationName:@"NOTIFICATION_NAME"                                                    object:nil];//或者用下面几行代码,明确的 notification 示例Test *test = [[Test alloc] init];NSNotification *notification = [NSNotification notificationWithName:@"NOTIFICATION_NAME"                                                             object:test];[[NSNotificationCenter defaultCenter] postNotification:notification];


示例,接受字体尺寸改变的广播

NSNotificationCenter *center = [NSNotificationCenter defaultCenter];[center addObserver:self           selector:@selector(fontSIzeChange:)               name:UIContentSizeCategoryDidChangeNotification             object:nil];
-(void)fontSIzeChange:(NSNotification *)notification{    // 处理字体尺寸改变的代码}




0 0
原创粉丝点击