有一次我在使用 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;
}
}
最佳答案
I'm confused why I didn't call "removeObserver:forKeyPath:" it shows different result on different sdk version.
那是因为不同的SDK版本不同。他们的行为不同。这就是“不同”的含义。。
请阅读发行说明,https://developer.apple.com/library/archive/releasenotes/Foundation/RN-Foundation/index.html :
Prior to 10.13 [and iOS 11], KVO would throw an exception if any observers were still registered after an autonotifying object's
-dealloc
finished running.
关于ios - 关于 KVO 在 iOS 10 和 iOS 11 中不带 `removeObserver:forKeyPath:` 的不同行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51800487/