TA的每日心情 | 汗 2024-10-15 10:05 |
---|
签到天数: 372 天 [LV.9]以坛为家II
|
本帖最后由 Sian 于 2014-5-19 11:40 编辑
通知是一种设计模式,与代理有类似的地方,一般实现分为几个步骤
1、设置监听
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(recive:) name:@"notification" object:nil];
2、发送通知
NSDictionary *dic = [NSDictionary dictionaryWithObject:@"value" forKey:@"key"];
[[NSNotificationCenter defaultCenter] postNotificationName:@"notification" object:nil userInfo:dic];
3、通知响应
- (void)recive:(NSDictionary *)userInfo
{
NSLog(@"%@", userInfo);
}
示例:- @implementation SAViewController
- -(id)init
- {
- if (self = [super init]){
- self.view.backgroundColor = [UIColor whiteColor];
-
- // 1、设置监听
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(recive:) name:@"notification" object:nil];
-
- // 创建一个按钮,当按钮点击时触发通知发送事件
- UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
- button.frame = CGRectMake(10, 50, 50, 30);
- [button setTitle:@"abc" forState:UIControlStateNormal];
- [self.view addSubview:button];
- [button addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];
- }
- return self;
- }
- - (void)buttonClick
- {
-
- // 2、发送通知
- NSDictionary *dic = [NSDictionary dictionaryWithObject:@"value" forKey:@"key"];
-
- [[NSNotificationCenter defaultCenter] postNotificationName:@"notification" object:nil userInfo:dic];
- }
- // 3、通知响应
- - (void)recive:(NSDictionary *)userInfo
- {
- NSLog(@"%@", userInfo);
- }
- @end
复制代码
|
|