iOS通知使用优化

在这里先简单的介绍一下通知的用法
1、通知的创建与发送

在需要发送通知的界面中创建通知

(1)添加字典, 将数据包到字典中

NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:@"xx",@"name"nil];

(2)创建通知

NSNotification *notification = [NSNotification notificationWithName:@"InfoNotification" object:nil userInfo:dict];

  (3)通过 通知中心 发送 通知

[[NSNotificationCenter defaultCenter] postNotification:notification];

2、通知的接收

在需要接收的控制器中注册通知监听者,将通知发送的信息接收

- (void)viewDidLoad{
    [super viewDidLoad];
    //获取通知中心单例对象
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    
    [center removeObserver:self name:@"loadCostPay" object:nil];
    [center addObserver:self selector:@selector(loadViewNotice:) name:@"loadCostPay" object:nil];
}

- (void)loadViewNotice:(NSNotification *)notification{
    //do something...
}

3、通知的移除

移除通知:removeObserver:和removeObserver:name:object:

其中,removeObserver:是删除通知中心保存的调度表一个观察者的所有入口,而removeObserver:name:object:是删除匹配了通知中心保存的调度表中观察者的一个入口。

通知在不使用了时一定要将其移除,因为它创建了之后会一直保存在内存中,只要添加了观察者并发送了通知,接收到以后就会调取通知中的方法

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"clear" object:self];
}

参考了Stack Overflow上的两篇文章,觉得老外在这通知上优化的要好一点,代码如下:

if (!opQ) {
        opQ = [[NSOperationQueue alloc] init];
    }
    __block id observer = [[NSNotificationCenter defaultCenter] addObserverForName:@"loadCostPay" object:nil queue:opQ usingBlock:^(NSNotification *aNotification) {
        dispatch_async(dispatch_get_main_queue(),
                       ^{
                           //do something...
                           [[NSNotificationCenter defaultCenter] removeObserver:observer];
                       });
    }];

参考文章链接

https://stackoverflow.com/questions/8477629/why-doesnt-remove-observer-from-nsnotificationcenteraddobserverfornameusingbl

https://stackoverflow.com/questions/10689295/multiple-block-operations-called-via-addobserverselectornameobject


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值