I have a class "Compass" which is intended to be the observer of another class "SensorA", "SensorB" oder "SensorC". The problem is I dont know the observed class before runtime. I used reflections in order to create an Instance while runtime. I don´t know if I´m practising KVO the right way when doing this.
---Another Extern Class--- Compass *aCompass= [[AnalogCompass alloc] initWithCompassName:@"ABC" andID...]; ---The oberserving Compass.m Class--- - (id)initWithCompassName:(NSString *)CompassName andIid:(int)Iid showAnalog:(NSString *)ShowAnalog showDigital:(NSString *)ShowDigital { if (self = [super init]) { super.iid = Iid; super.CompassName = CompassName; showAnalog=ShowAnalog; showDigital=ShowDigital; Class unknown_cls; unknown_cls = [[NSClassFromString(super.CompassName) alloc]init]; [unknown_cls addObserver:self forKeyPath:showAnalog options:NSKeyValueObservingOptionNew context:NULL]; [unknown_cls addObserver:self forKeyPath:showDigital options:NSKeyValueObservingOptionNew context:NULL]; } } - (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{ NSLog(@"IN?"); // [super observeValueForKeyPath:keyPath // // ofObject:object // // change:change // // context:context]; } ---Example of the oberserved SensorA Class--- @interface SensorA : NSObject { double xPosition; ... } @property (assign) double depthInFeet; - (id)initWithLineToParse:(NSArray *) fields; @end
When I´m doing a change like self.xposition = position; in any of my observed and reflected Sensor Classes (SensorA,SensorB,SensorC), the "observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context" in my observer Compass ist not called. Im guessing it has something to do with the reflection and maybe with related restrictions of this kind of technique. Or maybe because reflecting with
unknown_cls = [[NSClassFromString(super.CompassName) alloc]init];and not with
unknown_cls = [[NSClassFromString(super.CompassName) alloc]initWithLineToParse:array];
How to get this working for me? Is it the wrong attempt to observe like this maybe? Thanks for help.