Objective-C Tips & Trick - Prioregroup.com
[Objective-C] How to enable automatic observer notification
       
back

//
//  How to enable automatic observer notification
//
//  Created by Danilo Priore on 03/04/12.
//  Copyright (c) 2012 Prioregroup.com. All rights reserved.
//
#import <objc/runtime.h>

- (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];
}






Copyright © 1996-2018 Centro Studi Informatica di Danilo Priore. All rights reserved. P.I.10149810581.
prioregroup.com