iOS之NSNotificationCenter的使用

NSNotificationCenter(通知中心)的使用:
1.在需要接收通知的地方注册观察者
//获取通知中心单例对象
NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
//添加当前类对象为一个观察者,object设置为nil,表示接收一切通知
[center addObserver:self selector:@selector(getNotice:) name:@"notificationName" object:nil];

例:

//注册观察者      接收通知
 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getNotification:) name:@"notificationName" object:nil];

//接收到通知的操作
-(void) getNotification:(id)sender{
//接收的sender是发送的NSNotification通知
 NSLog(@"%@",sender);
 }

2.发送通知消息
//创建一个消息对象
//NSNotification通知 有三个属性name,object,userInfo
NSNotification * notice = [NSNotification notificationWithName:@"notificationName" object:nil userInfo:@{@"data":@"asd"}];
//发送消息
[[NSNotificationCenter defaultCenter]postNotification:notice];
我们可以在回调的函数中取到userInfo内容,如下:

发送通知的方法:

-(void)postNotification:(NSNotification *)notification;
-(void)postNotificationName:(NSNotificationName)aName object:(nullable id)anObject;
-(void)postNotificationName:(NSNotificationName)aName object:(nullable id)anObject userInfo:(nullable NSDictionary *)aUserInfo;

例:

[[NSNotificationCenter defaultCenter] postNotificationName:@"notificationName" object:nil userInfo:@{@"data":@"asd"}];

3.移除观察者 在哪个类注册的通知,就在哪个类移除观察者

- (void)dealloc {  
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

注意点:
1.注意要先注册再发送,不然先发送通知再注册,就接收不到通知了;
2.如果发送的通知指定了object对象,object对象可以是输入框等,那么观察者接收的通知设置的object对象与其一样,才会接收到通知,但是接收通知如果将这个参数设置为了nil,则会接收一切通知。
3.观察者的SEL函数指针可以有一个参数,参数就是发送的通知本身,可以通过这个参数取到消息对象的userInfo,实现传值。
4.从 iOS 9 开始通知中心会对观察者进行弱引用,所以不需要在观察者对象释放之前从通知中心移除。但是,通过-[NSNotificationCenter addObserverForName:object:queue:usingBlock]方法注册的观察者依然需要手动的释放,因为通知中心对它们持有的是强引用。适配iOS9以下的也需要手动移除观察者

当观察系统的通知时,不需要自己发送通知,只需注册,移除观察者就行
例:

//UIKeyboardWillShowNotification是系统的
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showKeyBoard) name:UIKeyboardWillShowNotification object:nil];

- (void)dealloc {
    //移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

可以点此查看demo

最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容