NSNotificationCenter removeObserver: in dealloc and thread-safety

前端 未结 3 1862
别跟我提以往
别跟我提以往 2021-02-03 14:12

I\'m using ARC and I\'m calling [[NSNotificationCenter defaultCenter] removeObserver:someObserver]; in observer\'s dealloc.

From NSNotification

3条回答
  •  太阳男子
    2021-02-03 14:46

    I just stumbled into this problem myself: I had one notification just in the process of being sent (which always happens in the main thread) while the object was in the process of being deallocated from a background thread. I fixed it by simply performing removeObserver in the main thread and waiting:

    - (void)removeNotificationCenterObserver
    {
        NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
        [notificationCenter removeObserver:self];
    }
    
    - (void)dealloc
    {
        [self performSelectorOnMainThread:@selector(removeNotificationCenterObserver) withObject:self waitUntilDone:YES];
    }
    

    This waits until the current run loop cycle ends and executes this message at the beginning of the next run loop cycle. This ensures that any functions that are still running will finish.

提交回复
热议问题