一聚教程网:一个值得你收藏的教程网站

热门教程

ios NSNotificationCenter通知的简单使用

时间:2022-06-25 23:30:30 编辑:袖梨 来源:一聚教程网

通知类本身比较简单,大概就分为注册通知监听器、发送通知,注销通知监听器三个方法;通知中心(NSNotificationCenter)采用单例的模式,整个系统只有一个通知中心,通过如下代码获取:

//获取通知中心
[NSNotificationCenter defaultCenter];

注册通知监听器方法:

//observer为监听器
//aSelector为接到收通知后的处理函数
//aName为监听的通知的名称
//object为接收通知的对象,需要与postNotification的object匹配,否则接收不到通知
- (void)addObserver:(id)observer selector:(SEL)aSelector name:(nullable NSNotificationName)aName object:(nullable id)anObject;

发送通知的方法:

//需要手动构造一个NSNotification对象
- (void)postNotification:(NSNotification *)notification;

//aName为注册的通知名称
//anObject为接受通知的对象,通知不传参时可使用该方法
- (void)postNotificationName:(NSNotificationName)aName object:(nullable id)anObject;

//aUserInfo为将要传递的参数,类型为字典类型
//通知需要传参数时使用下面这个方法,其他同上。
- (void)postNotificationName:(NSNotificationName)aName object:(nullable id)anObject userInfo:(nullable NSDictionary *)aUserInfo;

注销通知监听器方法:

//删除通知的监听器
- (void)removeObserver:(id)observer;
//删除通知的监听器,aName监听的通知的名称,anObject监听的通知的发送对象
- (void)removeObserver:(id)observer name:(nullable NSNotificationName)aName object:(nullable id)anObject;
//以block的方式注册通知监听器
- (id )addObserverForName:(nullable NSNotificationName)name object:(nullable id)obj queue:(nullable NSOperationQueue *)queue usingBlock:(void (^)(NSNotification *note))block API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0));

使用情况:

NSNotificationCenter类一般用于一个对象传递事件给另外一个对象,在另一个对象中触发某些方法,可以实现跨视图的交互。我在最近一个月内用到了两次NSNotificationCenter类。

①在对项目进行国际化时,在切换语言时采用通知的方式,使其他界面进行刷新(需要在主线程内)。

②使用SGPagingView时,需要实现pageContentView中的内容在多选状态时,pageTitleView禁止进行切换的功能。看了SGPagingView提供的方法是没有这个的,所以就采用了NSNotificationCenter。在进入多选状态时发一条通知,在退出多选状态时发一条通知(方法比较简陋,如果有更好的方法请不吝赐教)。

//注册通知监听器
  [NotifyUtil addNotify:NOTIFY_DISABLE_SWITCH Observer:self selector:@selector(disableSwitch) Object:nil];
  [NotifyUtil addNotify:NOTIFY_ALLOW_SWITCH Observer:self selector:@selector(allowSwitch) Object:nil];

//调用方法

//禁止pageTitleView进行切换
-(void)disableSwitch{
  self.pageTitleView.userInteractionEnabled = NO;
}
//允许pageTitleView进行切换
-(void)allowSwitch{
  self.pageTitleView.userInteractionEnabled = YES;
}

//注销通知监听器
- (void) dealloc{
  [NotifyUtil removeNotify:NOTIFY_DISABLE_SWITCH Observer:self];
  [NotifyUtil removeNotify:NOTIFY_ALLOW_SWITCH Observer:self];
}

注:用NotifyUtil对NSNotificationCenter类进行了一个简单的封装,参数基本都一致,就不贴NotifyUtil的代码了。

热门栏目