Cómo recibir notificaciones sobre cualquier cambio vinculante en un NSObjectController
-
21-12-2019 - |
Pregunta
Yo tengo un NSView
en el que todos los controles se han vinculado a un objeto modelo mediante un NSObjectController
en el Creador de interfaces.
Esto funciona correctamente.Ahora me gustaría mi NSViewController
para ser notificado cada vez que haya un cambio en cualquier de esas ataduras.es posible?¿Si es así, cómo?
Solución
Terminé observando al miembro de mi clase de modelo usando Kvo.Para automatizar el proceso (para que no tenga que escribir código para hacer esto para cada miembro de cada modelo) hice esto:
static void *myModelObserverContextPointer = &myModelObserverContextPointer;
- (void)establishObserversForPanelModel:(FTDisclosurePanelModel *)panelModel {
// Add observers for all the model's class members.
//
// The member variables are updated automatically using bindings as the user makes
// adjustments to the user interface. By doing this we can therefore be informed
// of any changes that the user is making without having to have a target action for
// each control.
unsigned int count;
objc_property_t *props = class_copyPropertyList([panelModel class], &count);
for (int i = 0; i < count; ++i){
NSString *propName = [NSString stringWithUTF8String:property_getName(props[i])];
[panelModel addObserver:self forKeyPath:propName options:0 context:&myModelObserverContextPointer];
}
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
// Check for insertions/deletions to the model
if (context == myModelObserverContextPointer) {
if ([_delegate respondsToSelector:@selector(changeMadeToPanelModel:keyPath:)]) {
[_delegate changeMadeToPanelModel:object keyPath:keyPath];
}
}
else
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow