Core Data dependent property on to-many relationship
I'm trying to update a custom property in an NSManagedObject whenever an item that it has a to-many relation to changes. I've overridden the following methods as prescribed by apple:
- (void)addDevicesObject:(Device *)value;
- (void)removeDevicesObject:(Device *)value;
- (void)addDevices:(NSSet *)value;
- (void)removeDevices:(NSSet *)value开发者_C百科;
and inside the implementation I add or remove observers on the changed objects. The problem is my override methods are not called when my bindings based UI makes changes to the data. How should I go about doing this?
If the custom property is calculated when it is asked for, use +keyPathsForValuesAffectingValueForKey: to trigger update notifications when devices is changed.
+ (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key {
if([key isEqualToString:@"MyCustomProperty"]) return [NSSet setWithObject:@"devices"];
return [super keyPathsForValuesAffectingValueForKey:key];
}
If you want to perform calculations when devices is changed only, then use KVO to get notified when it is changed.
//Put this in the various awake... methods
[self addObserver:self forKeyPath:@"devices" options:0 context:nil];
//Put this in the didTurnIntoFault method
[self removeObserver:self forKeyPath:@"devices"];
- (void)observeValueForKeyPath:(NSString *)path ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if(object == self && [path isEqualToString:@"devices"]) {
//Update custom property here
} else [super observeValueForKeyPath:path ofObject:object change:change context:context];
}
This is the same problem I solved in a little github project
Using observings to solve the problem is a possible way, still you need to consider many core data specific problems with faulting (observing a property of a faulting object) and undo/redo/delete. If you want to stay 10.5 compatible the important method awakeFromSnapshotEvent is also missing and you need a workaround to activate observings for undoing delete objects after a context save.
The setter:
- (void)setDevices:(NSSet *)newDevices
should also be called in bindings if you want to avoid observings which can be complicated. Setters are NOT called in undo/redo operations! So you should store your dependent value in a core data modeled property.
精彩评论