dispatch_async 重新使用时应用崩溃

dispatch_async crashes app when re-used

我正在使用 here 的解决方案来使 titleView clipsToBounds 始终为真。

我的 ViewController 中有这个并且运行良好,但是,如果我通过按后退按钮离开 ViewController 然后返回,它的应用程序会在 dispatch_async行。

- (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];
        });
    }
}

编辑:

我得到的唯一错误是:Thread 1: EXC_BAD_ACCESS (code=1, address=0x102d8860)

控制台不提供除 (lldb)

以外的任何信息

检查你的街区

if (self.navigationController.navigationBar.subviews.count > 1){
…

如果你从viewController出去,你必须移除Observer。

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    [self.navigationController.navigationBar.subviews[2]
     removeObserver:self 
     forKeyPath:@"clipsToBounds"];
}