您的位置:首页 > 其它

NSNotification通知

2016-04-22 17:08 155 查看
通知就是在需要的地方发出,在接受通知的地方发生通知内容。

有个界面 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];
}


接受通知页面必须把通知移除掉。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: