Search code examples
cocoakey-bindingskey-value-observingcocoa-bindingsnsdocktile

How to create a binding for NSApp.dockTile's


In IB it is easy to bind a label or text field to some controller's keyPath.

The NSDockTile (available via [[NSApp dockTile] setBadgeLabel:@"123"]) doesn't appear in IB, and I cannot figure out how to programmatically bind its "badgeLabel" property like you might bind a label/textfield/table column.

Any ideas?


Solution

  • NSDockTile doesn't have any bindings, so your controller will have to update the dock tile manually. You could do this using KVO which would have the same effect as binding it.

    Create a context as a global:

    
    static void* MyContext=(void*)@"MyContext";
    

    Then, in your init method:

    
    [objectYouWantToWatch addObserver:self forKeyPath:@"dockTileNumber" options:0 context:MyContext];
    

    You then have to implement this method to be notified of changes to the key path:

    - (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
    {
        if (context == MyContext) {
            [[NSApp dockTile] setBadgeLabel:[object valueForKeyPath:keyPath]];
        }
        else {
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    }
    

    Make sure you remove the observer when the controller object goes away.