2009-08-05 92 views
1

我现在已经弄清楚如何过滤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以某种方式结合在一起。

回答

1

我再次回答了我自己的问题,我也希望这会帮助其他人,让他们知道如何过滤NSTreeController。

为了使它从我的帖子上面的工作做到以下几点。

1.对于您的实体,将Class设置为我的Case JGManagedObject中的NSManagedObject子类。

alt text http://dvlp.me/c3k

2.对于您在IB搜索字段中设置的谓词格式要筛选(该属性在实体,对我来说是名称)的东西。

alt text http://dvlp.me/9k9rw