关于KVO在没有`removeObserver:forKeyPath:`的情况下在iOS10和iOS11中的不同行为

时间:2018-08-11 14:12:53

标签: ios crash ios10 ios11 key-value-observing

当我使用KVO时,忘记了调用“ removeObserver:forKeyPath:”。在iOS10模拟器上,模拟器崩溃了。但是在iOS11模拟器上,一切正常。没有内存泄漏也没有崩溃。

我很困惑为什么不调用“ removeObserver:forKeyPath:”会导致在不同的SDK版本上产生不同的结果。

这里是演示代码:

#import <UIKit/UIKit.h>
@interface GSObject : NSObject

@end
@interface GSObject ()

@property (nonatomic, assign) NSInteger integer;

@end

@implementation GSObject

- (instancetype)init {
    if (self = [super init]) {
        [self addObserver:self forKeyPath:@"integer" options:NSKeyValueObservingOptionInitial context:nil];
    }
    return self;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object 
change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void 
*)context {
    NSLog(@"%@",object);
}
@end

int main(int argc, char * argv[]) {
    @autoreleasepool {
        GSObject *object = [[GSObject alloc] init];
        object = nil;
    }
}

1 个答案:

答案 0 :(得分:1)

  

我很困惑为什么不叫“ removeObserver:forKeyPath:”,它在不同的sdk版本上显示不同的结果。

那是因为不同的SDK版本不同。他们的行为有所不同。这就是“不同”的手段

请阅读发行说明https://support.google.com/analytics/answer/1034823?hl=en&ref_topic=1032939

  

在10.13 [和iOS 11]之前,如果自动通知对象的-dealloc完成运行后仍然有任何观察者注册,则KVO将引发异常。