Search code examples
iosobjective-cdispatch-async

dispatch_async crashes app when re-used


I'm using a solution for here to make titleView clipsToBounds always true.

I have this in my ViewController and it works well, however, if I leave the ViewController by pressing the back button and then come back, it app crashes at the dispatch_async line.

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {

    if([object isEqual:[[self.navigationController.navigationBar subviews] objectAtIndex:2]]) {

        dispatch_async(dispatch_get_main_queue(), ^{

            [[self.navigationController.navigationBar subviews] objectAtIndex:2].clipsToBounds = NO;
            [self.navigationItem.titleView layoutIfNeeded];
        });
    }
}

Edit:

The only error I get is: Thread 1: EXC_BAD_ACCESS (code=1, address=0x102d8860)

The console doesn't provide any information other than (lldb)


Solution

  • You must removeObserver if you go out from viewController.

    - (void)viewWillDisappear:(BOOL)animated {
        [super viewWillDisappear:animated];
    
        [self.navigationController.navigationBar.subviews[2]
         removeObserver:self 
         forKeyPath:@"clipsToBounds"];
    }