Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

自动移除订阅 #4

Open
EnkiChen opened this issue Aug 10, 2015 · 3 comments
Open

自动移除订阅 #4

EnkiChen opened this issue Aug 10, 2015 · 3 comments

Comments

@EnkiChen
Copy link

在使用GLPubSub时,如果类A通过block订阅一个通知后,如果不在dealloc方法移除,这个block将会一直存在;这样将会导致对象被释放,当有对应的通知时还是会执行block,那么就必须在dealloc方法中调用,该操作是否可以放在GLPubSub中进行统一处理呢?

@allenhsu
Copy link
Contributor

理论上可以通过 Category 在所有 dealloc 方法中都主动 unsubscribeAll

@EnkiChen
Copy link
Author

是的,修改方案有多种,我想应该放到GLPubSub中统一处理,你看下一下方法是否可行?

  • (id)subscribe:(NSString *)eventName obj:(id)obj handler:(GLEventHandler)handler {
    weak __typeof(self) weakSelf = self;
    id observer = [[NSNotificationCenter defaultCenter] addObserverForName:eventName object:obj queue:_pubSubQueue usingBlock:^(NSNotification *note) {
    if ( nil != weakSelf ) {
    __strong typeof(weakSelf) strongSelf = weakSelf;
    GLEvent *event = [[GLEvent alloc] initWithName:eventName obj:note.object data:[note.userInfo objectForKey:kGLPubSubDataKey]];
    handler(event);
    }
    }];
    NSMutableDictionary *subscriptions = (NSMutableDictionary *)objc_getAssociatedObject(self, &kGLPubSubSubscriptionsKey);
    if (!subscriptions) {
    subscriptions = [[NSMutableDictionary alloc] init];
    objc_setAssociatedObject(self, &kGLPubSubSubscriptionsKey, subscriptions, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    NSMutableSet *observers = [subscriptions objectForKey:eventName];
    if (!observers) {
    observers = [[NSMutableSet alloc] init];
    [subscriptions setObject:observers forKey:eventName];
    }
    [observers addObject:observer];
    return observer;
    }

@EnkiChen
Copy link
Author

用上面方法实现存在,通知一直没有被移除,执行block不在调用,在Category中调用主动 unsubscribeAll会更好,改方法有打算做Pod库的更新吗?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants