Skip to content

Instantly share code, notes, and snippets.

@joerick
Last active December 19, 2018 09:35
Show Gist options
  • Save joerick/a0b87607e69071fa6a3c to your computer and use it in GitHub Desktop.
Save joerick/a0b87607e69071fa6a3c to your computer and use it in GitHub Desktop.
Weak KVO example
#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;
}
}
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
@danurna
Copy link

danurna commented Nov 27, 2017

Works great! Here is a Swift 4.0 version (but only of the observer part): https://gist.github.com/danurna/3b0c2ac973d07877a882644beec7e250

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment