NSNotificationCenter观察者模式

NSNotificationCenter实现了观察者模式,允许应用的不同对象间以松耦合的方式进行通信。

NSNotificationCenter相当于一个消息中心,首先由Observer组件向NSNotificationCenter进行注册—表明该Observer组件对哪些NSNotification感兴趣。

当Poster向NSNotificationCenter发送NSNotification之后,所有在NSNotificationCenter上注册过的、对该NSNotification感兴趣的Observer对会被激发。

NSNotification代表Poster与Observer之间的信息载体,该对象包含如下只读属性。

  • @property (readonly, copy) NSString *name;通知的名字
  • @property (nullable, readonly, retain) id object;通知的Poster
  • @property (nullable, readonly, copy) NSDictionary *userInfo;用于携带通知的附加信息

发送通知:

  1. - (void)postNotification:(NSNotification *)notification;

  2. - (void)postNotificationName:(NSString *)aName object:(nullable id)anObject;

  3. - (void)postNotificationName:(NSString *)aName object:(nullable id)anObject userInfo:(nullable NSDictionary *)aUserInfo;

注册通知:

  1. - (void)addObserver:(id)observer selector:(SEL)aSelector name:(nullable NSString *)aName object:(nullable id)anObject;
  2. - (id <NSObject>)addObserverForName:(nullable NSString *)name object:(nullable id)obj queue:(nullable NSOperationQueue *)queue usingBlock:(void (^)(NSNotification *note))block

    使用NSNotificationCenter除了可以监听系统组件发出的通知(系统已经命名好名称)之外,也可以监听程序自己发出的通知(通知名称由自己命名)。

监听系统组件发出的通知:

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(finishLaunching) name:UIApplicationDidFinishLaunchingNotification object:[UIApplication sharedApplication]];
}

-(void)finishLaunching{
    NSLog(@"finishLaunching");
}

监听自定义通知:

- (void)viewDidLoad {
    [super viewDidLoad];

    UIButton* poster=[[UIButton alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
    poster.backgroundColor=[UIColor redColor];
    [self.view addSubview:poster];

    [poster addTarget:self action:@selector(post) forControlEvents:UIControlEventTouchUpInside];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(whenClick:) name:@"click" object:nil];

}

-(void)post{
    NSNotification* notication=[[NSNotification alloc] initWithName:@"click" object:nil userInfo:@{@"name":@"ricky"}];
    [[NSNotificationCenter defaultCenter] postNotification:notication];
}

-(void)whenClick:(NSNotification*)notificaton{
    NSLog(@"name=%@",[notificaton.userInfo objectForKey:@"name"]);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值