美文网首页IOS三人行
通知NSNotificationCenter

通知NSNotificationCenter

作者: yi叶知秋 | 来源:发表于2016-06-30 11:23 被阅读99次

    添加通知

    //UIColor *color;
    //NSNotificationCenter  通知中心 ,单例类
    //单例类:在整个应用程序中只有一个对象,调用单利方法是,不管创建多少次,都是同一个对象
    //defaultCenter 时通知中心的单利方法
    NSNotificationCenter *notiCenter = [NSNotificationCenter defaultCenter];
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:color,@"color", nil];
    //postNotificationName 发通知
    //参数1.通知的名字2.由谁发送通知3.发通知是需要传递的参数
    [notiCenter postNotificationName:@"changeColor" object:self userInfo:dic];
    

    接收通知

    //参数1.由谁去接收通知2.接收到通知后,需要执行的方法,如果方法需要传参,参数是NSNotification的对象3.接受通知的名字,要和发送通知时名字保持一致(调频一致);如果写nil,默认接受所有的通知4.是否指定通知的发送者,指定接受某一个对象发送的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiceChangeColorNotification:) name:@"changeColor" object:nil];
    
    //接收到通知执行的方法
    -(void)receiceChangeColorNotification:(NSNotification*)noti
    {
    //noti.name 通知的名字
    //noti.object 通知的发送者
    //noti.userInfo 发送通知传递的参数
    NSLog(@"接受到了改变颜色的通知:%@__%@__%@",noti.name,noti.object,noti.userInfo);
    NSDictionary *dic = noti.userInfo;
    UIColor *color = [dic objectForKey:@"color"];
    self.view.backgroundColor = color;
    }
    

    当给一个已经释放的对象(如一个自定义类)发送通知时 系统会立即崩溃 解决办法是 在自定义类的 dealloc 方法中移除通知

    //移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"classOver" object:nil];
    

    系统自带的通知

    //应用程序进入到后台的通知
    //UIApplicationDidEnterBackgroundNotification 程序进图后台的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationGotoBackGround) name:UIApplicationDidEnterBackgroundNotification object:nil];
    //接受到键盘frame改变的通知
    //UIKeyboardWillChangeFrameNotification 键盘frame将要改变的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameChange:) name:UIKeyboardWillChangeFrameNotification object:nil];

    相关文章

      网友评论

        本文标题:通知NSNotificationCenter

        本文链接:https://www.haomeiwen.com/subject/vmoxjttx.html