Day 34: NSResponder actions (3)
Continuing the series, I’ll give an example of creating a toolbar item for an action. Again I am heavily relying on conventions with regards to action names and images. Keep in mind that all this stuff is in the base class and that subclasses can override any of the methods to customize behaviour. A good example of that is the -toolbar method that subclasses are supposed to override.
- (NSToolbarItem *)toolbarItemWithSize:(NSToolbarSizeMode)size
{
NSToolbarItem *item = [[NSToolbarItem alloc]
initWithItemIdentifier:[self identifier]];
[item setLabel:[self label]];
[item setPaletteLabel:[item label]];
[item setImage:[self imageForToolbarSize:size]];
[item setToolTip:[self tooltip]];
[item setTarget:self];
[item setAction:@selector(performAction:)];
return [item autorelease];
}
This method is calling a bunch of methods I haven’t mentioned before but they are easy to guess; the label just chopes away the MS prefix and Action suffix by default and the identifier just takes the class name. As much as possible I’ve tried to keep the methods as small as possible and everything that even remotely makes sense to override sits in its own method.