通知类本身比较简单,大概就分为注册通知监听器、发送通知,注销通知监听器三个方法;通知中心(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]; }
敢达决战官方正版 安卓版v6.7.9
下载敢达决战 安卓版v6.7.9
下载像素火影骨架佐助 (Perseverance Fire Shadow)手机版v1.16
下载要塞英雄 安卓版v33.20.0-39082670-Android
下载梦想城镇vivo最新版本 安卓版v12.0.1
梦想城镇vivo版是这款卡通风模拟经营类手游的渠道服版本,玩
怦然心动的瞬间 安卓版v1.0
怦然心动的瞬间是一款真人向的恋爱互动游戏,在游戏中玩家将扮演
曼尼汉堡店游戏 安卓版v1.0.3
曼尼汉堡店是一款非常好玩的精品恐怖类型冒险游戏,在这款游戏中
现代总统模拟器去广告版 安卓版v1.0.46
现代总统模拟器是一款休闲养成类游戏,可能对于不少的玩家来说都
现代总统模拟器付费完整版 安卓版v1.0.46
现代总统模拟器高级版在商店是需要付费的,相对于普通版本,高级