美文网首页
nsnotifation & GCD

nsnotifation & GCD

作者: 有理想有暴富的小青年 | 来源:发表于2017-11-29 23:02 被阅读2次

发送通知在哪个线程 那么接收到通知后处理也就在哪个线程中

苹果官方给我们提供的方法外,我们还可以利用基于block的NSNotification去实现,apple 从 ios4 之后提供了带有 block 的 NSNotification

-(id)addObserverForName:(NSString *)name

object:(id)obj

queue:(NSOperationQueue *)queue

usingBlock:(void(^)(NSNotification *note))block

其中:

观察者就是当前对象

queue 定义了 block 执行的线程,nil 则表示 block 的执行线程和发通知在同一个线程

block 就是相应通知的处理函数

这个 API 已经能够让我们方便的控制通知的线程切换。但是,这里有个问题需要注意。就是其 remove 操作。

原来的 NSNotification 的 remove 方式如下:

1

2

3

-(void)removeObservers{

[[NSNotificationCenterdefaultCenter]removeObserver:selfname:POST_NOTIFICATIONobject:nil];

}

但是带 block 方式的 remove 便不能像上面这样处理了。其方式如下

-(void)removeObservers{

if(_observer){

[[NSNotificationCenterdefaultCenter]removeObserver:_observer];

}

}

其中 _observer 是 addObserverForName 方式的 api 返回观察者对象

原文链接:http://m.blog.csdn.net/hmh007/article/details/61920956

相关文章

网友评论

      本文标题:nsnotifation & GCD

      本文链接:https://www.haomeiwen.com/subject/lhkmbxtx.html