NSNotification通知

通知就是在需要的地方发出,在接受通知的地方发生通知内容。
有个界面 root –> second –>There
在There页面发出通知 让root页面改变
There页面代码如下:

@interface ThereController ()
@property (nonatomic, strong)UIButton *buttons;
@end
@implementation ThereController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor lightGrayColor];
    // 定义一个button 在button按钮事件中触发通知事件
    self.buttons = [UIButton buttonWithType:UIButtonTypeCustom];
    self.buttons.frame = CGRectMake(100, 100, 50, 30);
    self.buttons.backgroundColor = [UIColor greenColor];
    [self.buttons addTarget:self action:@selector(notification) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.buttons];

}

- (void)notification {
    #pragma mark 如果要携带参数  用字典形式携带
    NSDictionary *dic = [[NSDictionary alloc]init];
    dic = @{@"123":@"key"};
    //  创建通知
    NSNotification *notification = [NSNotification notificationWithName:@"tongzhi" object:nil userInfo:dic];

    #pragma mark 下面是不携带参数的通知
    NSNotification *notification = [NSNotification notificationWithName:@"tongzhi" object:nil];
    //  发送通知
    [[NSNotificationCenter defaultCenter]postNotification:notification];
    [self.navigationController popToRootViewControllerAnimated:YES];
}

@end

在接受通知的页面进行通知注册
在root页面进行注册通知

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self addViews];

    // 注册通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(tongzhixiaoxi:) name:@"tongzhi" object:nil];

}

接受通知实现时需要实现的方法

#pragma mark 返回的时候回更新labels的值
- (void)tongzhixiaoxi:(NSNotification *)text
{
//    self.labels.text = text.userInfo[@"123"];
//    NSLog(@"%@", text);
    self.labels.text = @"今天很热";

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

接受通知页面必须把通知移除掉。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值