Advertisement
priore

How to enable automatic observer notification

Apr 3rd, 2012
836
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //
  2. //  How to enable automatic observer notification
  3. //
  4. //  Created by Danilo Priore on 03/04/12.
  5. //  Copyright (c) 2012 Prioregroup.com. All rights reserved.
  6. //
  7. #import <objc/runtime.h>
  8.  
  9. - (id)init {
  10.     if (self = [super init]) {
  11.         [self addObserverNotifications];
  12.     }
  13.  
  14.     return self;
  15. }
  16. - (void)addObserverNotifications {
  17.     unsigned int count = 0;
  18.     objc_property_t *propertys = class_copyPropertyList([self class], &count);
  19.     for (int i = 0; i < count; ++i) {
  20.         NSString *name = [NSString stringWithCString:property_getName(propertys[i]) encoding:NSUTF8StringEncoding];
  21.         [self addObserver:self forKeyPath:name options:NSKeyValueObservingOptionNew context:nil];
  22.     }
  23.     free(propertys);
  24. }
  25.  
  26. - (void)removeObserverNotifications {
  27.     unsigned int count = 0;
  28.     objc_property_t *propertys = class_copyPropertyList([self class], &count);
  29.     for (int i = 0; i < count; ++i) {
  30.         NSString *name = [NSString stringWithCString:property_getName(propertys[i]) encoding:NSUTF8StringEncoding];
  31.             [self removeObserver:self forKeyPath:name];
  32.     }
  33.     free(propertys);
  34. }
  35.  
  36. // override this method (viewcontroller)
  37. - (void)didChangeValueForKey:(NSString *)key {
  38.     id value = [self valueForKey:key];
  39.     // your code here...
  40. }
  41.  
  42. - (void)dealloc {
  43.     [self removeObserverNotifications];
  44.     [super dealloc];
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement