Skip to content

Instantly share code, notes, and snippets.

@priore
Created July 17, 2012 11:49
Show Gist options
  • Save priore/3128985 to your computer and use it in GitHub Desktop.
Save priore/3128985 to your computer and use it in GitHub Desktop.
How to enable automatic observer notification
//
// How to enable automatic observer notification
//
// Created by Danilo Priore on 03/04/12.
// Copyright (c) 2012 Prioregroup.com. All rights reserved.
//
- (id)init {
if (self = [super init]) {
[self addObserverNotifications];
}
return self;
}
- (void)addObserverNotifications {
unsigned int count = 0;
objc_property_t *propertys = class_copyPropertyList([self class], &count);
for (int i = 0; i < count; ++i) {
NSString *name = [NSString stringWithCString:property_getName(propertys[i]) encoding:NSUTF8StringEncoding];
[self addObserver:self forKeyPath:name options:NSKeyValueObservingOptionNew context:nil];
}
free(propertys);
}
- (void)removeObserverNotifications {
unsigned int count = 0;
objc_property_t *propertys = class_copyPropertyList([self class], &count);
for (int i = 0; i < count; ++i) {
NSString *name = [NSString stringWithCString:property_getName(propertys[i]) encoding:NSUTF8StringEncoding];
[self removeObserver:self forKeyPath:name];
}
free(propertys);
}
// override this method (viewcontroller)
- (void)didChangeValueForKey:(NSString *)key {
id value = [self valueForKey:key];
// your code here...
}
- (void)dealloc {
[self removeObserverNotifications];
[super dealloc];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment