Last active
December 19, 2018 09:35
-
-
Save joerick/a0b87607e69071fa6a3c to your computer and use it in GitHub Desktop.
Weak KVO example
This file contains hidden or 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
#import <Foundation/Foundation.h> | |
#import <objc/runtime.h> | |
@interface Person : NSObject | |
@property (strong) NSString *name; | |
@end | |
@interface Observer : NSObject | |
- (id)initObserving:(id)object keyPath:(NSString *)keyPath; | |
@property (assign) id observedObject; | |
@property (copy) NSString *keyPath; | |
@end | |
@implementation Person | |
- (void)dealloc | |
{ | |
NSLog(@"Person dealloc"); | |
} | |
@end | |
@implementation Observer | |
- (id)initObserving:(id)object keyPath:(NSString *)keyPath | |
{ | |
self = [super init]; | |
if (self) { | |
_observedObject = object; | |
_keyPath = keyPath; | |
[object addObserver:self forKeyPath:keyPath options:0 context:NULL]; | |
objc_setAssociatedObject(object, "observer", self, OBJC_ASSOCIATION_RETAIN_NONATOMIC); | |
} | |
return self; | |
} | |
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object | |
change:(NSDictionary *)change context:(void *)context | |
{ | |
NSLog(@"Change observed!"); | |
} | |
- (void)dealloc | |
{ | |
NSLog(@"Observer dealloc"); | |
[self.observedObject removeObserver:self forKeyPath:_keyPath]; | |
} | |
@end | |
int main(int argc, char *argv[]) { | |
@autoreleasepool { | |
{ | |
Person *p1 = [Person new]; | |
{ | |
Observer *o1 = [[Observer alloc] initObserving:p1 keyPath:@"name"]; | |
} | |
} | |
return 0; | |
} | |
} | |
This file contains hidden or 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
2016-03-16 13:52:15.933 KVO dealloc ordering[81591:15373864] Person dealloc | |
2016-03-16 13:52:15.934 KVO dealloc ordering[81591:15373864] Observer dealloc |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Works great! Here is a Swift 4.0 version (but only of the observer part): https://gist.github.com/danurna/3b0c2ac973d07877a882644beec7e250