ios - 关于 KVO 在 iOS 10 和 iOS 11 中不带 `removeObserver:forKeyPath:` 的不同行为

标签 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;
    }
}

最佳答案

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/

相关文章:

ios - 添加到核心数据时如何避免重复?

java - Eclipse Oxygen安装错误OS X 10.11.6

ios - 我如何从 UINavigationController 转到 UIViewController

ios - 在信标范围内时显示图像而不是颜色

javascript - 是否有针对这个模糊的几分钟 iOS 日期时间本地错误的修复程序?

ios - 释放CGImageRef以避免内存泄漏

windows - 为什么SDL_DisplayFormat崩溃?

ios - 即使用户覆盖 50 米,当 ios10 应用程序未在后台(暂停)运行时,如何每 n 秒获取一次当前 GPS 位置?

iphone - 核心数据 fetchRequest 给出了executeFetchRequest :error: <null> is not a valid NSFetchRequest

swift - 在 ViewController 之间传输 TextField 数据