Correct management of addObserverForName:object:queue:usingBlock:

后端 未结 4 510
礼貌的吻别
礼貌的吻别 2021-02-01 03:37

I\'m still new to blocks in objective-c and wondering if I have this psuedo code correct. I\'m not sure if it\'s enough to just remove the observer or if i have to call removeOb

4条回答
  •  悲哀的现实
    2021-02-01 04:25

    You should not unregister in the register block. Instead, store the token returned from addObserverForName (in this case, your scanComplete) as an instance variable or in a collection that is an instance variable, and unregister later when you're about to go out of existence (e.g. in dealloc). What I do is keep an NSMutableSet called observers. So:

    id ob = [[NSNotificationCenter defaultCenter] 
         addObserverForName:@"whatever" object:nil queue:nil 
         usingBlock:^(NSNotification *note) {
            // ... whatever ...
    }];
    [self->observers addObject:ob];
    

    And then later:

    for (id ob in self->observers)
        [[NSNotificationCenter defaultCenter] removeObserver:ob];
    self->observers = nil;
    

提交回复
热议问题