监听
通知的方法
发送通知
[NSNotificationCenter defaultCenter] postNotification:<#(nonnull NSNotification *)#>
[NSNotificationCenter defaultCenter] postNotificationName:<#(nonnull NSString *)#> object:<#(nullable id)#> userInfo:<#(nullable NSDictionary *)#>
[NSNotificationCenter defaultCenter] postNotificationName:<#(nonnull NSString *)#> object:<#(nullable id)#>
接收通知
[NSNotificationCenter defaultCenter] addObserverForName:<#(nullable NSString *)#> object:<#(nullable id)#> queue:<#(nullable NSOperationQueue *)#> usingBlock:<#^(NSNotification * _Nonnull note)block#>
[NSNotificationCenter defaultCenter] addObserver:<#(nonnull NSObject *)#> forKeyPath:<#(nonnull NSString *)#> options:<#(NSKeyValueObservingOptions)#> context:<#(nullable void *)#>
[NSNotificationCenter defaultCenter] addObserver:<#(nonnull id)#> selector:<#(nonnull SEL)#> name:<#(nullable NSString *)#> object:<#(nullable id)#>
注销通知
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
监听字典里的值
添加观察者
NSMutableDictionary *dic = [NSMutableDictionary new];
[dic addObserver:self forKeyPath:@"username" options:NSKeyValueObservingOptionNew context:nil];
[dic setObject:@"2132132" forKey:@"username"];
值改变后,调用的方法:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
NSLog(@"%@",object);
}
注销观察者
-(void)dealloc{
[dic removeObserver:self forKeyPath:@"username"];
}
监听键盘
- UIKIT_EXTERN NSString *const UIKeyboardWillShowNotification;
- UIKIT_EXTERN NSString *const UIKeyboardDidShowNotification;
- UIKIT_EXTERN NSString *const UIKeyboardWillHideNotification;
- UIKIT_EXTERN NSString *const UIKeyboardDidHideNotification;
添加观察者
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillShowdEvent:) name:UIKeyboardWillShowNotification object:nil];
接收到通知,调用方法:
- (void)keyBoardWillShowdEvent:(NSNotification *)notification{
NSLog(@"%@",notification.userInfo);
}
注销观察者
-(void)dealloc{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
网友评论