Objective-C中的发通知的(Notification)

第一个页面进来后,先注册监听

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //先在通知中心注册
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doSomething:) name:NOTIFICATION_MESSAGE object:nil];
}



- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    
   // [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}

-(void)doSomething:(NSNotification *)notification
{
    
    //接受消息
    NSDictionary *Info = [notification userInfo];
    //输出收到的信息
    NSLog(@“消息收到:%@", Info[@"notification"]);
}


第二个页面进来后点击button 然后发消息

@implementation ChatViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self initContentView];
}

- (void)initContentView
{
    UIButton *_commitBtn = [[UIButton alloc]initWithFrame:CGRectMake(15, 179, kDEVICEWIDTH-30, 45)];
    _commitBtn.backgroundColor = [UIColor grayColor];
    [_commitBtn addTarget:self action:@selector(commitClick) forControlEvents:UIControlEventTouchUpInside];
    [_commitBtn setTitle:@"发消息" forState:UIControlStateNormal];
    _commitBtn.titleLabel.textColor = [UIColor whiteColor];
    _commitBtn.layer.cornerRadius = 4;
    [self.view addSubview:_commitBtn];

}

- (void)commitClick
{
    [self sendMessage];
}

#pragma mark - NSNotification method

-(void)sendMessage
{
    //把要发送的信息放入字典中
    NSDictionary *message = @{@"notification" : @“NSNotification消息测试通过!”};
    
    //创建通知对象
    NSNotification * notification = [NSNotification notificationWithName:NOTIFICATION_MESSAGE object:self userInfo:message];
    
    //向通知中心发送消息(发布消息)
    //[[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_MESSAGE object:nil];
    //向通知中心发送消息(发布消息)
    [[NSNotificationCenter defaultCenter] postNotification:notification];
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值