Using predicates on an array controller to filter related objects

hekevintran picture hekevintran · May 12, 2009 · Viewed 8.1k times · Source

I have an application using Core Data and bindings. I want to have an NSSearchField that can search through an NSArrayController bound to an NSTableView. The array controller contains Core Data objects that have a "name" field. I have setup the NSSearchField like this:

Bind To: the array controller
Controller Key: filterPredicate
Predicate Format: name contains[c] $value

This works. I want to extend it so that it can search to the fields of objects related to those in the array controller. Each object in the array controller has a to-many relationship to another type of object called "tag" which has a field called "name". I tried the following:

Bind To: the array controller
Controller Key: filterPredicate
Model Key Path: tags
Predicate Format: name contains[c] $value

This however does not work. Nothing happens in the NSTableView when text is input into the NSSearchField. What is wrong with it?

Answer

Barry Wark picture Barry Wark · May 12, 2009

Binding to tags as the model key path attempts to bind the search field predicate to the key path arrayController.filterPredicate.tags. Since the filterPredicate property of the array controller doesn't have a tags property, you're probably gettings 'key not found' exceptions that are being logged silently. Instead, recalling that the filterPredicate of an NSArrayController is applied to the members of the array, you want the binding to be set up something like this:

Bind To: <array controller>
Controller Key: filterPredicate
Predicate Format: ANY self.tags contains[c] $value

self.tags could be written as just tags, but I think this makes it clearer that tags is a property of the object to which the predicate is being applied.