我现在已经弄清楚如何过滤NSTreeController,做到这一点我有NSManagedObject子类,并添加了一些代码到我的应用程序委托,我也绑定了我的NSSearchField到我的应用程序委托的filterPredicate但我想我需要以某种方式连接我的NSTreeController和NSSearchField以使其工作。 下面我已经发布了所有我已经使用过的代码,试着让它工作。过滤树控制器
NSManagedObject子类头文件。
@interface Managed_Object_Sub_Class : NSManagedObject {
NSArray *filteredChildren; // this should fix the compiler error
}
- (NSArray *)filteredChildren;
@end
NSManagedObject子类实现文件。
@implementation Managed_Object_Sub_Class
static char *FilteredChildrenObservationContext;
- (id)initWithEntity:(NSEntityDescription *)entity insertIntoManagedObjectContext:(NSManagedObjectContext *)context {
if (self = [super initWithEntity:entity insertIntoManagedObjectContext:context]) {
[[NSApp delegate] addObserver:self forKeyPath:@"filterPredicate" options:0 context:&FilteredChildrenObservationContext];
[self addObserver:self forKeyPath:@"subGroup" options:0 context:&FilteredChildrenObservationContext];
}
return self;
}
// use finalize with GC
- (void)dealloc {
[[NSApp delegate] removeObserver:self forKeyPath:@"filterPredicate"];
[self removeObserver:self forKeyPath:@"subGroup"];
[super dealloc];
}
- (NSArray *)filteredChildren {
if (filteredChildren == nil) {
NSPredicate *predicate = [[NSApp delegate] filterPredicate];
if (predicate)
filteredChildren = [[[self valueForKey:@"subGroup"] filteredArrayUsingPredicate:predicate] copy];
else
filteredChildren = [[self valueForKey:@"subGroup"] copy];
}
return filteredChildren;
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if (context == &FilteredChildrenObservationContext) {
[self willChangeValueForKey:@"filteredChildren"];
[filteredChildren release];
filteredChildren = nil;
[self didChangeValueForKey:@"filteredChildren"];
} else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
@end
代码添加到应用程序委托头文件
NSPredicate *filterPredicate;
代码添加到应用程序委托实现文件
- (NSPredicate *)filterPredicate {
return filterPredicate;
}
- (void)setFilterPredicate:(NSPredicate *)newFilterPredicate {
if (filterPredicate != newFilterPredicate) {
[filterPredicate release];
filterPredicate = [newFilterPredicate retain];
}
}
搜索字段绑定
alt text http://snapplr.com/snap/vs9q
这还没有工作,所以这就是为什么我问什么,我需要在这里做的,使其工作,就像我说的,我想我需要连接NSSearchField和NSTreeController以某种方式结合在一起。