NSNotificationCenter通知
NSNotificationCenter
发布通知监听通知- 需要先监听,再发布
//创建一个通知的发布者
NotificationSender *sender1 = [[NotificationSender alloc] init];
//创建一个通知的监听者
NSNotificationListener *listener1 = [[NSNotificationListener alloc] init];
//先获取NSNotificationCenter对象
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
//监听一个通知
[notificationCenter addObserver: listener1 selector:@selector(listen) name:@"tongzhi1" object:sender1 ];
//让sender1对象发布一个通知
//通过NSNotificationCenter发布一个通知
[notificationCenter postNotificationName:@"tongzhi1",object:sender1,userInfo:@{@"title":@"start!!",@"content":@"hello!"}];
通知的监听
- 需要设置监听者监听发布者的通知,调用监听者哪个方法
//监听一个通知
[notificationCenter addObserver: (id) selector:(SEL) name:(NSString *) object:(id)];
addObserver:监听的对象
selector:方法
name:通知的名字,如果为nil,则监听该对象全部内容
object:通知的发布者,如果为nil,则全部name都会监听
name,object同时nil,所有对象所有通知都要监听,一般不使用
- 例子(取出数据要注意,特别是
bool
类型)
[KNotificationCenter addObserverForName:KNotificationMsgNumSuccess object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
NSNumber *intNum = note.userInfo[@"msgFlag"];
self.msgFlag = [intNum integerValue];
self.navNoticeBtn.qmui_badgeInteger = self.msgFlag;
}];
自定义的类NSNotificationListener需要添加监听方法,用于被通知时被调用
-(void)listen()
{}
通知的发布
void postNotification:(NSNotification *)
需要传入NSNotification对象
void postNotificationName:(NSString *) object:(id)
传入NSString帮你封装
void postNotificationName:(NSString *) object:(id) userInfo:(NSDictionary *)
传入NSString,NSDictionary帮你封装
NSString:通知名称 object:发送通知的对象 userInfo:字典,通知的内容
通知的移除
避免造成野指针,对象销毁之后,需要移除通知
监听者类需要增加方法
-(void)dealloc{
//移出通知
[[NSNotificationCenter defaultCenter] removeObserver: self];
//ARC下不需要调用父类的dealloc方法
}
NSNotification对一个通知的封装
自定义的类NSNotificationListener需要添加监听方法,用于被通知时被调用
该方法可以传参数
-(void)listen1:(NSNotification *)noteInfo
{
//userInfo能收到
noteInfo.name;
noteInfo.object;
noteInfo.userInfo;
}
监听设备旋转、电池电量改变、贴近脸部(近距离传感器)等事件
通过通知,
UIDevice
类提供了一个单例对象,它代表着设备,通过它可以获得一些设备相关的信息,比如电池电量值batteryLevel
、电池状态batteryState
、设备的类型model
,比如iPod
、iphone
等、设备的系统systemversion
通过[UIDevice currentDevice]
可以获取这个单例对象
UIDevice
对象会不间断地发布一些通知,下列是UIDevice
对象所发布通知的名称常量
UIDeviceOrientationDidChangeNotification//设备旋转
UIDeviceBatteryStateDidChangeNotification//电池状态改变
UIDeviceBatteryLevelDidChangeNotification//电池电量改变
UIDeviceProximityStateDidChangeNotification//近距离传感器(比如设备贴近了使用者的脸部)
UIDevice *dev = [UIDevice currentDevice];
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self selector: @selector(m1:) name:UIDeviceOrientationDidChangeNotification object:dev];