Last active
March 24, 2019 07:02
-
-
Save kingcos/36575befa94a464d7aff689daa34f5d6 to your computer and use it in GitHub Desktop.
StackOverflow - https://stackoverflow.com/questions/55321440/do-i-have-to-removeobserver-in-kvo-manually-now
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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