Don't like ads? PRO users don't see any ads ;-)

How to enable automatic observer notification

By: priore on Apr 3rd, 2012  |  syntax: Objective C  |  size: 1.30 KB  |  hits: 88  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  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. - (id)init {
  8.         if (self = [super init]) {
  9.                 [self addObserverNotifications];
  10.         }
  11.  
  12.         return self;
  13. }
  14. - (void)addObserverNotifications {
  15.     unsigned int count = 0;
  16.     objc_property_t *propertys = class_copyPropertyList([self class], &count);
  17.     for (int i = 0; i < count; ++i) {
  18.         NSString *name = [NSString stringWithCString:property_getName(propertys[i]) encoding:NSUTF8StringEncoding];
  19.         [self addObserver:self forKeyPath:name options:NSKeyValueObservingOptionNew context:nil];
  20.     }
  21.     free(propertys);
  22. }
  23.  
  24. - (void)removeObserverNotifications {
  25.     unsigned int count = 0;
  26.     objc_property_t *propertys = class_copyPropertyList([self class], &count);
  27.     for (int i = 0; i < count; ++i) {
  28.         NSString *name = [NSString stringWithCString:property_getName(propertys[i]) encoding:NSUTF8StringEncoding];
  29.             [self removeObserver:self forKeyPath:name];
  30.     }
  31.     free(propertys);
  32. }
  33.  
  34. // override this method (viewcontroller)
  35. - (void)didChangeValueForKey:(NSString *)key {
  36.         id value = [self valueForKey:key];
  37.         // your code here...
  38. }
  39.  
  40. - (void)dealloc {
  41.         [self removeObserverNotifications];
  42.         [super dealloc];
  43. }