弱引用'关联'关联对象中的对象

时间:2015-12-15 10:09:28

标签: objective-c uiscrollview automatic-ref-counting weak-references associated-object

以下代码导致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

0 个答案:

没有答案