自动移除observer的KVO和Notification

作者: KevinTing | 来源:发表于2016-08-13 15:57 被阅读1267次

仿照https://github.com/X-Team-X/SimpleKVO写的,添加KVO和Notification观察者非常容易,自动移除observer。不需要手动在dealloc中添加如下代码:

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillEnterForegroundNotification object:nil];
    [self.tableView removeObserver:self forKeyPath:NSStringFromSelector(@selector(contentOffset))];
}

用block的方式传回回调,而且也不用担心没有移除observer导致的crash了,用法如下:

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.tableView addObserverForKeyPath:NSStringFromSelector(@selector(contentOffset)) block:^(__weak id obj, id oldValue, id newValue) {
        NSLog(@"old value:%@ new value:%@", NSStringFromCGPoint([oldValue CGPointValue]), NSStringFromCGPoint([newValue CGPointValue]));
    }];
    [self addNotificationForName:UIApplicationWillEnterForegroundNotification block:^(NSNotification *notification) {
        NSLog(@"will enter forground");
    }];
}

自动移除observer的原理很简单,因为我们一般在dealloc方法里面做remove observer的操作。那么就hook dealloc方法就好了:

// 替换dealloc方法,自动注销observer
+ (void)load
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Method originalDealloc = class_getInstanceMethod(self, NSSelectorFromString(@"dealloc"));
        Method newDealloc = class_getInstanceMethod(self, @selector(autoRemoveObserverDealloc));
        method_exchangeImplementations(originalDealloc, newDealloc);
    });
}

- (void)autoRemoveObserverDealloc
{
    if (objc_getAssociatedObject(self, &KTKvoObserversKey) || objc_getAssociatedObject(self, &KTNotificationObserversKey)) {
        [self removeAllObserverBlocks];
        [self removeAllNotificationBlocks];
    }
    // 下面这句相当于直接调用dealloc
    [self autoRemoveObserverDealloc];
}

完整项目在这里SimpleKVONotification

相关文章

  • 自动移除observer的KVO和Notification

    仿照https://github.com/X-Team-X/SimpleKVO写的,添加KVO和Notificat...

  • iOS 如何自动移除KVO观察者

    iOS 如何自动移除KVO观察者

  • iOS KVO使用小坑

    这个版本接手selfStrong的代码的时候,在移除KVO的observer的时候一直挂,经排查发现,原来这个KV...

  • iOS面试题-每日十道-第七天

    一. Notification和KVO有什么不同?KVO在ObjC中是怎么实现的? KVO:只能监听属性值的变化...

  • Notification和KVO

    Notification KVO objc swift

  • 问题

    1. Notification和KVO有什么不同?KVO在ObjC中是怎么实现的? KVO:只能监听属性值的变化,...

  • iOS KVO

    KVO主要的几个方法 添加观察者 移除观察者 观察回调 参数说明:observer:观察者,一般传self。key...

  • 心动

    KVO,delegate和notification是A和B双方合作的事情,而KVO是B单方面的事情。 A有消息了,...

  • KVO的原理实现

    一、什么是KVO KVO和Notification是Objective-C语言中观察者模式的两种实现机制。KVO指...

  • KVO

    KVO 添加 addObserver:forKeyPath: options:context: observer ...

网友评论

    本文标题:自动移除observer的KVO和Notification

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