In the header file
#import <Cocoa/Cocoa.h> @interface BWSearchArrayController : NSArrayController { NSString *searchString; } - (IBAction) search: (id) sender; @end // BWSearchArrayControllerand then in the implementation:
// returns an array containing the content of the objects arranged // with the user's critera entered into the search box thingie - (NSArray *) arrangeObjects: (NSArray *) objects { // result of the filtering NSArray *returnObjects = objects; // if there is a search string, use it to compare with the // search field string if (searchString != nil) { // where to store the filtered NSMutableArray *filteredObjects; filteredObjects = [NSMutableArray arrayWithCapacity: [objects count]]; // walk the enumerator NSEnumerator *enumerator = [objects objectEnumerator]; id item; // actully BWFileEntries while (item = [enumerator nextObject]) { // get the filename from the entry NSString *filename; filename = [item valueForKeyPath: @"fileName"]; // see if the file name matches the search string NSRange range; range = [filename rangeOfString: searchString options: NSCaseInsensitiveSearch]; // found the search string in the file name, add it to // the result set if (range.location != NSNotFound) { [filteredObjects addObject: item]; } } returnObjects = filteredObjects; } // have the superclass arrange them too, to pick up NSTableView sorting return ([super arrangeObjects:returnObjects]); } // arrangeObjectsand then to set the search string:
- (void) setSearchString: (NSString *) string { [searchString release]; if ([string length] == 0) { searchString = nil; } else { searchString = [string copy]; } } // setSearchString - (void) search: (id) sender { [self setSearchString: [sender stringValue]]; [self rearrangeObjects]; } // search
observeValueForKeyPath:ofObject:change:context:
, (or you do override it but don't handle your callbacks) you'll generally get an exception.
This trains you to do it right and never call super for the callbacks you're handling, or you'll get an exception.
Except
if you've added KVO to a subclass of NSArrayController
(and possibly all controller types), and don't call super's observeValueForKeyPath:ofObject:change:context:
, bindings won't work at all, with no warning/notice/nothing. (Courtesy of Duncan Wilcox)
In Interface Builder, drag over the NSSearchField, and bind the predicate
like this:
what contains[c] $value
(assuming the attribute you're filtering is called what
)