Why doesn't Remove Observer from NSNotificationCenter:addObserverForName:usingBlock get called

前端 未结 2 1171
面向向阳花
面向向阳花 2020-12-05 15:56

I\'m confused on why the observer is never removed in the following code. In my viewDidAppear I have the following:

-(void)viewDidAppear:(BOOL)animated{

id         


        
2条回答
  •  天涯浪人
    2020-12-05 16:23

    I find that in fact there is a memory leak unless the observer is marked both __block and __weak. Use Instruments to make sure that self is not being overretained; I bet it is. This, however, works correctly (from my actual code):

    __block __weak id observer = [[NSNotificationCenter defaultCenter] 
        addObserverForName:@"MyMandelbrotOperationFinished" 
        object:op queue:[NSOperationQueue mainQueue] 
        usingBlock:^(NSNotification *note) {
            // ... do stuff ...
            [[NSNotificationCenter defaultCenter] 
                removeObserver:observer 
                name:@"MyMandelbrotOperationFinished" 
                object:op];
    }];
    

提交回复
热议问题