Search code examples
objective-ccocoa-bindingsnsmenuitem

Display Model's Data in NSMenuItem


I'd like to display some data of my model within a status bar menu. So, I bound my entity-object to the title of an NSMenuItem:

        [self.statusMenu setAutoenablesItems:NO];

        NSMenuItem * exportMenuItem = [[NSMenuItem alloc] init];
        [exportMenuItem bind:@"title" toObject:expo withKeyPath:@"menuItemTitle" options:nil];
        [exportMenuItem setEnabled:NO];

        [self.statusMenu insertItem:exportMenuItem atIndex:3];

It works fine so far from init. But when I update my Model it does not updates the title of the NSMenuItem.


Solution

  • For reference, the canonical solution to this issue is to implement a class method like this:

    + (NSSet *)keyPathsForValuesAffectingMenuItemTitle
    {
        return [NSSet setWithObjects: @"propertyMenuItemTitleDependsOn1", 
                                      @"propertyMenuItemTitleDependsOn2",
                                      nil];
    }
    

    If you implement a method like this, then the framework will handle calling willChangeValueForKey: and didChangeValueForKey: for the key menuItemTitle any time any of the other properties are changed.