我在XCode 9.3,objective-c,OSX而不是iOS。
我在我的应用程序中使用NSPredicateEditor,到目前为止工作正常。但是,我有一个视图,它将使用编辑器中设置的谓词更新其内容(基本上视图显示过滤的数组(。
目前我有一个"刷新"按钮,用户在编辑器中更改某些内容后需要点击以更新视图。
我想知道是否有办法触发我的方法在添加或更改谓词行时自动更新视图?
我试图将观察者添加到NSPredicateEditor.objectValue - 但我没有收到通知。
- (void)viewWillAppear {
[self.predicateEditor.objectValue addObserver:self selector:@selector(predicateChangedByUser:) name:@"Test" object:nil];
}
- (void)predicateChangedByUser:(NSNotification*)aNotification {
NSLog(@"Changed: %@",aNotification);
}
任何帮助表示赞赏
您没有收到通知,因为您正在尝试合并通知和 KVO。一些解决方案:
解决方案 A:将谓词编辑器的操作连接到操作方法。
解决方案 B:遵守通知NSRuleEditorRowsDidChangeNotification
。
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(predicateChangedByUser:) name:NSRuleEditorRowsDidChangeNotification object:self.predicateEditor];
- (void)predicateChangedByUser:(NSNotification *)notification {
NSLog(@"predicateChangedByUser");
}
解决方案 C:观察谓词编辑器的键路径predicate
。 predicate
是NSRuleEditor
的属性。
static void *observingContext = &observingContext;
[self.predicateEditor addObserver:self forKeyPath:@"predicate" options:0 context:&observingContext];
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if (context == &observingContext)
NSLog(@"observeValueForKeyPath %@", keyPath);
else
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
解决方案 D:将编辑器的值绑定到谓词属性。
"NSPredicateEditor"有一个"action"选择器,可以在代码中使用接口设计器中的出口连接到函数,如下所示:
- (IBAction)predicateChanged:(id)sender {
// Update your view
}