ios NSNotificationCenter 学习使用

Android里面发消息可以用广播,也可以自己定义一套框架,比如eventbus,iOS也有自己原生的消息框架--NSNotificationCenter

这里简单记录下怎么使用NSNotificationCenter类,直接贴代码:

//
//  ViewController.m
//  NotificationTest
//
//  Created by  Alex on 2017/3/26.
//  Copyright © 2017年 alex. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [[  defaultCenter] addObserver:self selector:@selector(notice:) name:@"notify1" object:nil];

    [_mBtnSend addTarget:self action:@selector(sendNotify) forControlEvents:UIControlEventTouchUpInside];
    [_mBtnRemove addTarget:self action:@selector(removeNotify) forControlEvents:UIControlEventTouchUpInside];
}

/** 发送通知*/
- (void)sendNotify {
    NSLog(@"%s", "sendNotify");
    [[NSNotificationCenter defaultCenter] postNotificationName:@"notify1" object:@"888"];
}

/** 注销通知*/
- (void)removeNotify {
    NSLog(@"%s", "removeNotify");
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}

/** 接受消息*/
- (void)notice:(NSNotification *)sender {
    NSLog(@"%s", "接受到消息");
    NSLog(@"%@", sender.object);
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

打印记录

2017-03-27 12:02:03.198 NotificationTest[3623:308708] sendNotify

2017-03-27 12:02:03.200 NotificationTest[3623:308708]接受到消息

2017-03-27 12:02:03.200 NotificationTest[3623:308708] 888

2017-03-27 12:02:26.500 NotificationTest[3623:308708] removeNotify


[NSNotificationCenter defaultCenter] 调用这个方法是单例模式的,所以可以直接这么写

注意:如果添加了一个观察者作为接受消息的对象,那么销毁这个对象时需要注销掉这个观察者




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值