ios NSNotificationCenter通知的简单使用
通知类本身比较简单,大概就分为注册通知监听器、发送通知,注销通知监听器三个方法;通知中心(NSNotificationCenter)采用单例的模式,整个系统只有一个通知中心,通过如下代码获取:
//获取通知中心 [NSNotificationCenterdefaultCenter];
注册通知监听器方法:
//observer为监听器 //aSelector为接到收通知后的处理函数 //aName为监听的通知的名称 //object为接收通知的对象,需要与postNotification的object匹配,否则接收不到通知 -(void)addObserver:(id)observerselector:(SEL)aSelectorname:(nullableNSNotificationName)aNameobject:(nullableid)anObject;
发送通知的方法:
//需要手动构造一个NSNotification对象 -(void)postNotification:(NSNotification*)notification; //aName为注册的通知名称 //anObject为接受通知的对象,通知不传参时可使用该方法 -(void)postNotificationName:(NSNotificationName)aNameobject:(nullableid)anObject; //aUserInfo为将要传递的参数,类型为字典类型 //通知需要传参数时使用下面这个方法,其他同上。 -(void)postNotificationName:(NSNotificationName)aNameobject:(nullableid)anObjectuserInfo:(nullableNSDictionary*)aUserInfo;
注销通知监听器方法:
//删除通知的监听器 -(void)removeObserver:(id)observer; //删除通知的监听器,aName监听的通知的名称,anObject监听的通知的发送对象 -(void)removeObserver:(id)observername:(nullableNSNotificationName)aNameobject:(nullableid)anObject; //以block的方式注册通知监听器 -(id)addObserverForName:(nullableNSNotificationName)nameobject:(nullableid)objqueue:(nullableNSOperationQueue*)queueusingBlock:(void(^)(NSNotification*note))blockAPI_AVAILABLE(macos(10.6),ios(4.0),watchos(2.0),tvos(9.0));
使用情况:
NSNotificationCenter类一般用于一个对象传递事件给另外一个对象,在另一个对象中触发某些方法,可以实现跨视图的交互。我在最近一个月内用到了两次NSNotificationCenter类。
①在对项目进行国际化时,在切换语言时采用通知的方式,使其他界面进行刷新(需要在主线程内)。
②使用SGPagingView时,需要实现pageContentView中的内容在多选状态时,pageTitleView禁止进行切换的功能。看了SGPagingView提供的方法是没有这个的,所以就采用了NSNotificationCenter。在进入多选状态时发一条通知,在退出多选状态时发一条通知(方法比较简陋,如果有更好的方法请不吝赐教)。
//注册通知监听器 [NotifyUtiladdNotify:NOTIFY_DISABLE_SWITCHObserver:selfselector:@selector(disableSwitch)Object:nil]; [NotifyUtiladdNotify:NOTIFY_ALLOW_SWITCHObserver:selfselector:@selector(allowSwitch)Object:nil]; //调用方法 //禁止pageTitleView进行切换 -(void)disableSwitch{ self.pageTitleView.userInteractionEnabled=NO; } //允许pageTitleView进行切换 -(void)allowSwitch{ self.pageTitleView.userInteractionEnabled=YES; } //注销通知监听器 -(void)dealloc{ [NotifyUtilremoveNotify:NOTIFY_DISABLE_SWITCHObserver:self]; [NotifyUtilremoveNotify:NOTIFY_ALLOW_SWITCHObserver:self]; }
注:用NotifyUtil对NSNotificationCenter类进行了一个简单的封装,参数基本都一致,就不贴NotifyUtil的代码了。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。