Skip to content

Instantly share code, notes, and snippets.

@kingcos
Last active March 24, 2019 07:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kingcos/36575befa94a464d7aff689daa34f5d6 to your computer and use it in GitHub Desktop.
Save kingcos/36575befa94a464d7aff689daa34f5d6 to your computer and use it in GitHub Desktop.
//
// ViewController.m
// KVOC
//
// Created by kingcos on 2019/3/24.
// Copyright © 2019 kingcos. All rights reserved.
// This is the demo code for my question:
// https://stackoverflow.com/questions/55321440/do-i-have-to-removeobserver-in-kvo-manually-now
//
#import "ViewController.h"
@interface Computer : NSObject
@property (nonatomic, assign) double memoryPercentage;
@end
@implementation Computer
- (instancetype)init
{
self = [super init];
if (self) {
[self addObserver:self forKeyPath:NSStringFromSelector(@selector(memoryPercentage)) options:NSKeyValueObservingOptionNew context:nil];
}
return self;
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
NSLog(@"change - %@", change[NSKeyValueChangeNewKey]);
}
@end
@interface ViewController ()
@property (nonatomic, strong) Computer *cpt;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_cpt = [[Computer alloc] init];
}
- (IBAction)updated:(id)sender {
self.cpt.memoryPercentage += 0.1;
}
- (IBAction)removed:(id)sender {
[self.cpt removeObserver:self.cpt forKeyPath:@"memoryPercentage"];
}
- (IBAction)setToNil:(id)sender {
self.cpt = nil;
}
- (IBAction)initAgain:(id)sender {
self.cpt = [[Computer alloc] init];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment