过滤树控制器

时间:2009-08-05 16:13:15

标签: objective-c cocoa

我现在几乎想出了如何过滤NSTreeController,为了做到这一点,我已经对NSManagedObject进行了分类,并在我的App Delegate中添加了一些代码,我还将我的NSSearchField绑定到了我的App Delegate的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 个答案:

答案 0 :(得分:0)

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

要从上面的帖子开始工作,请执行以下操作。

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

alt text http://dvlp.me/c3k

2.对于IB中的搜索字段,将谓词格式设置为您要过滤的内容(实体中的属性,对我而言,它是名称)。

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

相关问题