iOS开发之UI开发(通知)

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,比如iPodiphone等、设备的系统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];
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值