以下代码导致NSInternalConsistencyException:dealloc
。
实际上,问题是当在Observer上调用_removeObservers
时,它对UIScrollView的引用已经被稀释,unsafe_unretained
是一个无操作。
我知道这可能与关联对象被解除分配的方式有关,但实际上并不清楚https://developer.apple.com/videos/play/wwdc2011-322/(38:14)中关联对象被删除之前弱参考被删除。
我找到的解决方法是创建UIScrollView属性@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
然后:
npm-mssql