One Quickie


Hooking up a search box to your array controller (Bindings->General)
Tiger supposedly does this for us. If you're having to support Panther as well, here's a way to have a search box filter the contents managed by an NSArrayController.

In the header file

#import <Cocoa/Cocoa.h>

@interface BWSearchArrayController : NSArrayController
{
    NSString *searchString;
}

- (IBAction) search: (id) sender;

@end // BWSearchArrayController
and 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]);

} // arrangeObjects
and 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



borkware home | products | miniblog | rants | quickies | cocoaheads
Advanced Mac OS X Programming book

webmonster@borkware.com