美文网首页
给通知和KVO添加block实现

给通知和KVO添加block实现

作者: 咔咔尼亜 | 来源:发表于2019-03-06 17:56 被阅读0次

给通知和KVO添加block实现

给通知添加block的实现

  1. 创建NSObject分类并创建分类方法(带通知名参数和block回调参数)
  if (!name || !block) return;
    dispatch_semaphore_t notificationSemaphore = [self _xw_getSemaphoreWithKey:XWNotificationSemaphoreKey];
    dispatch_semaphore_wait(notificationSemaphore, DISPATCH_TIME_FOREVER);
    NSMutableDictionary *allTargets = objc_getAssociatedObject(self, XWNotificationBlockKey);
    if (!allTargets) {
        allTargets = @{}.mutableCopy;
        objc_setAssociatedObject(self, XWNotificationBlockKey, allTargets, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    _XWBlockTarget *target = allTargets[name];
    if (!target) {
        target = [_XWBlockTarget new];
        allTargets[name] = target;
        [[NSNotificationCenter defaultCenter] addObserver:target selector:@selector(xw_doNotification:) name:name object:nil];
    }
    [target xw_addNotificationBlock:block];
    [self _xw_swizzleDealloc];
    dispatch_semaphore_signal(notificationSemaphore);

如果通知名为空或者block为空直接返回,调用懒加载方法_xw_getSemaphoreWithKey获取信号量对象,信号量等待,懒加载获取关联属性targets字典,从targets字典中取出对应通知名的target对象(如果没有就创建一个,并保存到字典中,将给系统的通知中心注册observer为target的通知,执行方法为target中的方法,target的方法中调用block),通知中心添加对应的通知名的通知,target的blockset添加对应的block
当调用分类的发送通知的方法的时候,利用系统的通知中心发送通知,target对象的就能收到通知,target对象调用block,分类中注册通知方法中的block被调用,完成回调

给KVO添加block回调的实现

调用分类的addObserver方法,懒加载创建信号量,信号量等待,通过关联属性方法获取block字典,如果没有分类关联属性,则创建并设置关联属性,通过可以path从关联属性字典中获取到target,如果target为空则创建target对象,并将target对象保存到字典,将target对象设置为本方法调用者的监听也就是调用addObserver方法。路径为keypath,如果target对象存在则直接给target对象的block数组中添加block。发送信号,取消信号量限制。

- (void)xw_addObserverBlockForKeyPath:(NSString*)keyPath block:(void (^)(id obj, id oldVal, id newVal))block {
   if (!keyPath || !block) return;
   dispatch_semaphore_t kvoSemaphore = [self _xw_getSemaphoreWithKey:XWKVOSemaphoreKey];
   dispatch_semaphore_wait(kvoSemaphore, DISPATCH_TIME_FOREVER);
   //取出存有所有KVOTarget的字典
   NSMutableDictionary *allTargets = objc_getAssociatedObject(self, XWKVOBlockKey);
   if (!allTargets) {
       //没有则创建
       allTargets = [NSMutableDictionary new];
       //绑定在该对象中
       objc_setAssociatedObject(self, XWKVOBlockKey, allTargets, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
   }
   //获取对应keyPath中的所有target
   _XWBlockTarget *targetForKeyPath = allTargets[keyPath];
   if (!targetForKeyPath) {
       //没有则创建
       targetForKeyPath = [_XWBlockTarget new];
       //保存
       allTargets[keyPath] = targetForKeyPath;
       //如果第一次,则注册对keyPath的KVO监听
       [self addObserver:targetForKeyPath forKeyPath:keyPath options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:NULL];
   }
   [targetForKeyPath xw_addBlock:block];
   //对第一次注册KVO的类进行dealloc方法调剂
   [self _xw_swizzleDealloc];
   dispatch_semaphore_signal(kvoSemaphore);
}

target对象实现observer代理方法,当观察的keypath发生变化的时候,target枚举自己block数组中的block并一一调用。

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
   if (!_kvoBlockSet.count) return;
   BOOL prior = [[change objectForKey:NSKeyValueChangeNotificationIsPriorKey] boolValue];
   //只接受值改变时的消息
   if (prior) return;
   NSKeyValueChange changeKind = [[change objectForKey:NSKeyValueChangeKindKey] integerValue];
   if (changeKind != NSKeyValueChangeSetting) return;
   id oldVal = [change objectForKey:NSKeyValueChangeOldKey];
   if (oldVal == [NSNull null]) oldVal = nil;
   id newVal = [change objectForKey:NSKeyValueChangeNewKey];
   if (newVal == [NSNull null]) newVal = nil;
   //执行该target下的所有block
   [_kvoBlockSet enumerateObjectsUsingBlock:^(void (^block)(__weak id obj, id oldVal, id newVal), BOOL * _Nonnull stop) {
       block(object, oldVal, newVal);
   }];
}

移除通知和观察者

- (void)xw_removeNotificationForName:(NSString *)name{
   if (!name) return;
   NSMutableDictionary *allTargets = objc_getAssociatedObject(self, XWNotificationBlockKey);
   if (!allTargets.count) return;
   _XWBlockTarget *target = allTargets[name];
   if (!target) return;
   dispatch_semaphore_t notificationSemaphore = [self _xw_getSemaphoreWithKey:XWNotificationSemaphoreKey];
   dispatch_semaphore_wait(notificationSemaphore, DISPATCH_TIME_FOREVER);
   [[NSNotificationCenter defaultCenter] removeObserver:target];
   [allTargets removeObjectForKey:name];
   dispatch_semaphore_signal(notificationSemaphore);
   
}

- (void)xw_removeAllNotification{
   NSMutableDictionary *allTargets = objc_getAssociatedObject(self, XWNotificationBlockKey);
   if (!allTargets.count) return;
   dispatch_semaphore_t notificationSemaphore = [self _xw_getSemaphoreWithKey:XWNotificationSemaphoreKey];
   dispatch_semaphore_wait(notificationSemaphore, DISPATCH_TIME_FOREVER);
   [allTargets enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, _XWBlockTarget *target, BOOL * _Nonnull stop) {
       [[NSNotificationCenter defaultCenter] removeObserver:target];
   }];
   [allTargets removeAllObjects];
   dispatch_semaphore_signal(notificationSemaphore);
}

相关文章

  • 给通知和KVO添加block实现

    给通知和KVO添加block实现 给通知添加block的实现 创建NSObject分类并创建分类方法(带通知名参数...

  • ios开发中使用RAC代替block传值

    RAC可以实现KVO、代理、通知、block的功能,可谓集多功能于一身。本篇文章介绍RAC是如何代替block传值...

  • RAC

    代理、通知、block、kvo、Target都属于响应式编程 ReactiveObjc和通知有点像,但是RAC里创...

  • iOS 杂记 持续更新中

    一、导航栏透明界面下移 二、添加host域名 三、block未实现的闪退信息 四、KVO 五、GCD概念 http...

  • KVO,NSNotification,delegate及bloc

    KVO,NSNotification,delegate及block区别 KVO就是cocoa框架实现的观察者模式,...

  • OC 底层(KVC、KVO、Delegate、Category、

    目录 1.KVC2.KVO3.通知4.代理、委托、协议5.Block、KVO、通知、代理之间的区别6.分类 Cat...

  • 代理/通知/block/KVO

    代理: 第一就是代理,这也是很常用的方式,特点是一对一的形式,而且逻辑结构非常清晰。实现起来较为简单:1.声明协议...

  • 代理/通知/block/KVO

    代理: 代理是 iOS 很常用的方式,它的特点就是一对一的形式,并且它的逻辑结构非常的清晰。实现起来也是比较简单的...

  • 代理、Block、通知、KVO

    1.代理代理是:。 2.Blockdelegate和block的作用都是用于两个类之间的回传数据,即当一个类创建了...

  •  KVO,NSNotification,delegate及blo

    KVO,NSNotification,delegate及block区别KVO就是cocoa框架实现的观察者模式,是...

网友评论

      本文标题:给通知和KVO添加block实现

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