Search code examples
objective-cmacoscocoanstoolbar

NSToolbarDelegate Error?


Im creating a NSWindowController and its window programatically. So i create a simple NSToolbar with:

NSToolbar *toolbar = [[NSToolbar alloc] initWithIdentifier:@"PreferencesToolbar"];

[toolbar setDisplayMode:NSToolbarDisplayModeIconAndLabel];
[toolbar setAllowsUserCustomization:NO];
[toolbar setAutosavesConfiguration:NO];

[self.window setToolbar:toolbar];

[toolbar release];

Which all works fine, but when I add [toolbar setDelegate:self];

I get the following error:

ERROR: invalid delegate (does not implement all required methods), and so can not be used! (To debug, add a breakpoint to NSToolbarError

According to NSToolbarDelegate there are no required methods, so what is going wrong here?


Solution

  • In order to make the toolbar work with your NSWindowController subclass as its delegate, you must declare it to conform to NSToolbarDelegate protocol :

    @interface MyController : NSWindowController <NSToolbarDelegate>
    

    Also, from the doc, you must ensure that some are implemented, even if they are optional, because you created the toolbar programmatically. They are :

    -(NSToolbarItem *)toolbar:(NSToolbar *)toolbar
        itemForItemIdentifier:(NSString *)itemIdentifier
    willBeInsertedIntoToolbar:(BOOL)flag;
    
    -(NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)toolbar;
    
    -(NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar *)toolbar;
    

    Important While this method is marked as @optional in the NSToolbarDelegate protocol , it must be implemented if the associated toolbar is created programatically. Toolbars created in Interface Builder can implement this method to augment functionality.