Sian 发表于 2014-5-19 11:37:20

通知机制

本帖最后由 Sian 于 2014-5-19 11:40 编辑

通知是一种设计模式,与代理有类似的地方,一般实现分为几个步骤

1、设置监听

      [ addObserver:self selector:@selector(recive:) name:@"notification" object:nil];

2、发送通知

      NSDictionary *dic = ;
   
      [ postNotificationName:@"notification" object:nil userInfo:dic];

3、通知响应

      - (void)recive:(NSDictionary *)userInfo
      {
                  NSLog(@"%@", userInfo);
      }

示例:
@implementation SAViewController

-(id)init
{
    if (self = ){
      self.view.backgroundColor = ;
      
      // 1、设置监听
      [ addObserver:self selector:@selector(recive:) name:@"notification" object:nil];
      
      // 创建一个按钮,当按钮点击时触发通知发送事件
      UIButton *button = ;
      button.frame = CGRectMake(10, 50, 50, 30);
      ;
      ;
      ;
    }
    return self;
}

- (void)buttonClick
{
   
    // 2、发送通知
    NSDictionary *dic = ;
   
    [ postNotificationName:@"notification" object:nil userInfo:dic];

}

// 3、通知响应
- (void)recive:(NSDictionary *)userInfo
{
    NSLog(@"%@", userInfo);
}
@end




页: [1]
查看完整版本: 通知机制