Objective-C: Where to remove observer for NSNotification?

前端 未结 14 1671
北海茫月
北海茫月 2020-11-29 19:37

I have an objective C class. In it, I created a init method and set up a NSNotification in it

//Set up NSNotification
[[NSNotificationCenter defaultCenter] a         


        
14条回答
  •  佛祖请我去吃肉
    2020-11-29 19:43

    It is important to notice also that viewWillDisappear is called also when the view controller present a new UIView. This delegate simply indicate that the view controller main view is not visible on the display.

    In this case, deallocating the notification in viewWillDisappear may be inconvenient if we are using the notification to allow the UIview to communicate with the parent view controller.

    As a solution I usually remove the observer in one of these two methods:

    - (void)viewWillDisappear:(BOOL)animated {
        NSLog(@"viewController will disappear");
        if ([self isBeingDismissed]) {
            NSLog(@"viewController is being dismissed");
            [[NSNotificationCenter defaultCenter] removeObserver:self name:@"actionCompleted" object:nil];
        }
    }
    
    -(void)dealloc {
        NSLog(@"viewController is being deallocated");
        [[NSNotificationCenter defaultCenter] removeObserver:self name:@"actionCompleted" object:nil];
    }
    

    For similar reasons, when I issue the notification the first time, I need to account for the fact that any time a view with appear above the controller then viewWillAppear method is fired. This will in turn generate multiple copy of the same notification. Since there isn't a way to check if a notification is already active, I obviate the problem by removing the notification before adding it:

    - (void)viewWillAppear:(BOOL)animated {
        NSLog(@"viewController will appear");
        // Add observers
        [[NSNotificationCenter defaultCenter] removeObserver:self name:@"imageGenerated" object:nil]; // This is added to avoid duplicate notifications when the view is presented again
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receivedImageFromCameraOrPhotolibraryMethodOnListener:) name:@"actionCompleted" object:nil];
    
    }
    

提交回复
热议问题