iOS开发中,每一个app都有一个通知中心,通知中心能够发送和接收通知。app
在使用通知中心 NSNotificationCenter以前,先了解一下通知 NSNotification。函数
NSNotification 能够理解为消息对象,包含三个成员变量,以下: post
@property (readonly, copy) NSString *name; @property (nullable, readonly, retain) id object; @property (nullable, readonly, copy) NSDictionary *userInfo;
name:通知的名称spa
object:针对某一个对象的通知code
userInfo:字典类型,主要是用来传递参数server
建立并初始化一个NSNotification能够使用下面的方法:对象
+ (instancetype)notificationWithName:(NSString *)aName object:(nullable id)anObject; + (instancetype)notificationWithName:(NSString *)aName object:(nullable id)anObject userInfo:(nullable NSDictionary *)aUserInfo;
NSNotificationCenter 通知中心,是一个单例。只能使用 [NSNotificationCenter defaultCenter] 获取通知中心对象。blog
发送通知能够使用下面的方法:开发
[[NSNotificationCenter defaultCenter] postNotificationName:@"testNotification" object:nil];
或者:rem
NSDictionary *userInfo = @{@"name":@"John",@"age":@"15"};
NSNotification *notice = [NSNotification notificationWithName:@"testNotification" object:nil userInfo:userInfo]; [[NSNotificationCenter defaultCenter] postNotification:notice];
添加一个观察者的方法(能够理解成在某个观察者中注册通知):
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(haveNoti:) name:@"testNotification" object:nil];
有四个参数:第一个参数是观察者,也就是谁注册这个通知;第二个参数是当接收到通知时的回调函数;第三个参数是通知的名称,通知名是区分各个通知的惟一标识;第四个参数是接收哪一个对象发过来的通知,若是为nil,则接收任何对象发过来的该通知。
移除观察者,两种方法:
- (void)removeObserver:(id)observer; - (void)removeObserver:(id)observer name:(NSString *)aName object:(id)anObject;
NSNotificationCenter 的使用举例以下:
发送通知(两种方法):
- (void)btnClicked { //[[NSNotificationCenter defaultCenter] postNotificationName:@"testNotification" object:nil]; NSDictionary *userInfo = @{@"name":@"John",@"age":@"15"}; NSNotification *notice = [NSNotification notificationWithName:@"testNotification" object:nil userInfo:userInfo]; [[NSNotificationCenter defaultCenter] postNotification:notice]; }
增长观察者:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(haveNoti:) name:@"testNotification" object:nil];
回调函数(能够利用回调函数的参数 notification得到该通知的信息,好比name、object、参数):
- (void)haveNoti:(NSNotification *)notification { NSLog(@"name = %@",[notification name]); NSDictionary *userInfo = [notification userInfo]; NSLog(@"info = %@",userInfo); }
针对某一个特定对象的通知的使用场景:
UITextField,好比说咱们要监听UITextField 里面内容的变化,此时能够注册下面的通知:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(searchBarTextChange) name:UITextFieldTextDidChangeNotification object:self.searchBar];
self.searchBar 是 UITextField 类型。