2

以下代码导致 NSInternalConsistencyException: Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'An instance 0x7fd3a1010000 of class UIScrollView was deallocated while key value observers were still registered with it.

实际上,问题是当dealloc在 Observer 上调用时,它对 UIScrollView 的引用已经被取消,并且_removeObservers是无操作的。

我知道这可能与释放关联对象的方式有关,但这实际上从https://developer.apple.com/videos/play/wwdc2011-322/ (38:14) 中不清楚对象在弱引用被擦除之前被擦除。

我发现的一种解决方法是制作 UIScrollView 属性unsafe_unretained

  • 有人确切知道为什么会发生这种情况吗?
  • 这里推荐的解决方案是什么?

谢谢!

@interface Observer : NSObject
@property (nonatomic, weak) UIScrollView *scrollView;
@end

@implementation Observer

- (void)dealloc {
    [self _removeObservers];
}

- (void)setScrollView:(UIScrollView *)scrollView {
    if (_scrollView) {
        [self _removeObservers];
    }
    _scrollView = scrollView;
    [self.scrollView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];
}

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

- (void)_removeObservers {
    [self.scrollView removeObserver:self forKeyPath:@"contentOffset"];
}

@end

@interface UIScrollView (Test)
@end

@implementation UIScrollView (Test)

- (void)test_setup {
    Observer *observer = [Observer new];
    observer.scrollView = self;
    objc_setAssociatedObject(self, @"observer", observer, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end

接着:

UIScrollView *scrollView = [UIScrollView new];
[scrollView test_setup];
// scrollView is deallocated <--- EXCEPTION
4

0 回答 0