One Quickie

Adding your own objects to the responder chain (NSObject->General)
For I project I was working on, I needed the editing tools (for a graphical editor) to be in the responder chain so they could react to menu items. Doing this was surprisingly easy.

First step was to make the tools inherit from NSResponder:

@interface BWTool : NSResponder
    // blah
// ... more blah
@end // BWTool
Then, in the view class where the tool gets set, put the tool in the responder chain by setting its next responder to be the view's current next responder. If a different tool gets set, take the current tool's next responder and give it to the new tool. Otherwise the view gets its original next responder back:
- (void) setTool: (BWTool *) newTool
    NSResponder *nextResponder;

    // this is the next element in the chain

    if (currentTool != nil) {
        nextResponder = [currentTool nextResponder];
    } else {
        nextResponder = [self nextResponder];

    // decide who gets to point to the next responder

    if (newTool != nil) {
        // stick the tool into the chain
        [self setNextResponder: newTool];
        [newTool setNextResponder: nextResponder];

    } else {
        // cut the tool out of the chain (if there was one)
        [self setNextResponder: nextResponder];

    [newTool retain];
    [currentTool release];

    currentTool = newTool;

} // setDrawTool
And now tools can have action methods, and menu items that enable and disable appropriately.

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