365Cocoa

A snippet of Objective-C code per day, 365 days long.
Written by Pieter Omvlee, developer and owner of Bohemian Coding.

Apr 6

Day 37: NSResponder actions (5)

A few days ago I showed how I initialized all my actions, and keep in mind I stored all of them in a dictionary. Today I’ll go from toolbar actions to a full toolbar. We start with this dictionary of actions we already have but note that we probably have actions we don’t want in our toolbar. I gave action a -showInToolbar method that subclasses override, similarly there is an -isSelectable method. Below is a quick outline of my MSToolbarConstructor class:

- (NSArray *)allActions
{
  return [[actions allValues] filterUsingBlock:^(id object) {
    return [object showInToolbar];
  }];
}
- (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)toolbar
{
  return [[[self allActions] valueForKey:@"identifier"]
    arrayByAddingObjectsFromArray:[self standardToolbarIdentifiers]];
}
- (NSArray *)toolbarSelectableItemIdentifiers:(NSToolbar *)toolbar
{
  return [[[self allActions] filterUsingBlock:^(id object) {
    return [object isSelectable];
  }] valueForKey:@"identifier"];
}
- (NSToolbarItem *)toolbar:(NSToolbar *)toolbar
itemForItemIdentifier:(NSString *)itemIdentifier
 willBeInsertedIntoToolbar:(BOOL)flag
{
  return [[actions valueForKey:itemIdentifier] 
  toolbarItemWithSize:[toolbar sizeMode]];
}

Keep in mind that this series about NSResponder-based actions is not as much to share individual tips (I presume you know how to use NSToolbarItem) but more to outline the a particular line of thought I’ve followed for my app. I hope that you find it somehow thought-provoking, even if you disagree. And of course if you do, I’d love to hear from you.


  1. 365cocoa posted this