观察者模式:关于通知的使用(NSNotificationCenter)

时间:2023-03-09 08:45:43
观察者模式:关于通知的使用(NSNotificationCenter)

一.通知的使用方法

  1.发出通知

    例如:[[NSNotificationCenter defaultCenter]postNotificationName:@"backToFirstPage" object:@"123321"];

    通知的名字叫做backToFirstPage,而123321是一个参数,类型为ID类型,一般用于传值的

  2.接受通知

    例如:[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiceNot:) name:@"backToFirstPage" object:nil];

    观察者就是self

    接收通知的名字:backToFirstPage

    接收到后调用的函数- (void)receiceNot:(NSNotification)nt{};nt.objet 就是发出通知传过来的参数@"123321"

  3.移除通知

    例如:[[NSNotificationCenter defaultCenter]removeObserver:self name:@"backToFirstPage" object:nil];

二:常用场景

   通知属于一对多的,可以用于发出通知可以被多个类同时接收,这个于代理不相同,代理是一对一的。

三:注意事项

  1.发出通知以后,当另一个类接收到了通知,如果不需要持续监听的情况下,最好是立即移除监听。因为这个类释放了的时候,还没有移除监听的话,程序会出现异常崩溃。

  2.接收通知后,只要这个类没有被释放,就会持续的监听这个通知。

  3.移除通知以后,该类将不再接收通知(只是不接收名为“backToFirstPage”)的通知

四:程序中常用的一些监听方法

  1.键盘监听

  [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWasShown:)
                                                 name:UIKeyboardDidShowNotification object:nil];
     [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardDidHidden:)
                                                 name:UIKeyboardDidHideNotification object:nil];
    //添加切入后台切回前台监听didEnterBackground:
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(didEnterBackground:)
                                                 name:UIApplicationDidEnterBackgroundNotification object:nil];
    //监听后台返回前台的时候调用willEnterForeground:
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(willEnterForeground:)
                                                 name:UIApplicationWillEnterForegroundNotification object:nil];

  //监听后台返回前台的时候调用willEnterForeground:

  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(becomeActive:) name:UIApplicationDidBecomeActiveNotification object:nil];

  //如果程序在前台运行, 也就是播放讲解。此时来了个电话或者闹铃, 会触发

  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioInterruption:)  name:AVAudioSessionInterruptionNotification object:nil];