NSNotificationCenter

时间:2022-06-10 17:01:25

- (void)viewDidLoad {

[super viewDidLoad];

UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];

btn.frame = CGRectMake(100, 100, 100, 50);

btn.backgroundColor = [UIColor grayColor];

[btn setTitle:@"click me" forState:UIControlStateNormal];

[btn addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:btn];

// 注册消息

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNoticeMessage:) name:@"test" object:@"notice-recieve"];

}

-(void)clickAction:(id)sender

{

// 能接受消息

[[NSNotificationCenter defaultCenter] postNotificationName:@"test" object:@"notice-recieve"];

// 不能接收到消息,object 对象不一致

[[NSNotificationCenter defaultCenter] postNotificationName:@"test" object:@"notice-recieve111"];

}

// 处理消息

-(void)handleNoticeMessage:(id)sender

{

NSLog(@"handleNoticeMessage sender = %@", sender);

}

-(void)viewWillDisappear:(BOOL)animated

{

// 移除通知

[[NSNotificationCenter defaultCenter]removeObserver:self];

}