我有一个可进行KVO的类(称之为
设置
这个示例在
(请注意,“受影响的关键路径 = 受影响的值”不在其中。)
似乎
此外,涉及 (NSObjectController 的子类的) 实例的任何关键路径都不会影响其他关键路径,例如:
我该如何在这种情况下声明关键路径之间的依赖关系?为什么会发生这样的事情?
(是的,我知道有
Observee
),其affectedValue
动态属性受到affectingValue
属性的影响。属性之间的依赖关系通过实现+keyPathsForValuesAffectingAffectedValue
方法来定义。设置
affectingValue
的值会通知affectedValue
已经被更改,就像我所期望的那样,除非Observee
是NSObjectController
的子类。以下是完整的示例:@interface Observee : NSObject // or NSObjectController
@property (readonly, strong, nonatomic) id affectedValue;
@property (strong, nonatomic) id affectingValue;
@property (strong, nonatomic) NSArrayController *arrayController;
@end
@implementation Observee
@dynamic affectedValue;
- (id)affectedValue { return nil; }
+ (NSSet *)keyPathsForValuesAffectingAffectedValue {
NSLog(@"keyPathsForValuesAffectingAffectedValue called");
return [NSSet setWithObject:@"affectingValue"];
}
@end
@interface AppDelegate : NSObject <NSApplicationDelegate>
@property (strong, nonatomic) Observee *observee;
@end
@implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)notification {
self.observee = [[Observee alloc] init];
[self.observee addObserver:self
forKeyPath:@"affectedValue"
options:NSKeyValueObservingOptionNew
context:NULL];
NSLog(@"setting value to affectingValue");
self.observee.affectingValue = @42;
}
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {
NSLog(@"affected key path = %@", keyPath);
}
@end
这个示例在
Observee
派生自 NSObject
时可以正常运行,并输出以下内容:keyPathsForValuesAffectingAffectedValue called
setting value to affectingValue
affected key path = affectedValue
当Observee
从NSObjectController
继承时:
keyPathsForValuesAffectingAffectedValue called
setting value to affectingValue
(请注意,“受影响的关键路径 = 受影响的值”不在其中。)
似乎
keyPathsForValuesAffectingAffectedValue
在两种情况下都被调用,但后者是无操作的。此外,涉及 (NSObjectController 的子类的) 实例的任何关键路径都不会影响其他关键路径,例如:
@implementation SomeObject
// `someValue` won't be affected by `key.path.(snip).arrangedObjects`
+ (NSSet *)keyPathsForValuesAffectingSomeValue {
return [NSSet setWithObject:@"key.path.involving.anNSArrayController.arrangedObjects"];
}
@end
我该如何在这种情况下声明关键路径之间的依赖关系?为什么会发生这样的事情?
(是的,我知道有
will/didChangeValueForKey:
和相关的内容,但是用另一个setter来包装每个影响到的关键路径很糟糕,我想避免它。)
KVO
的奇怪行为。 - Colas+ (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key
吗? - Colas+keyPathsForValuesAffectingValueForKey:
的默认实现只是搜索+keyPathsForValuesAffecting<Key>
并返回其结果,覆盖它在这里没有任何区别。 - uasi