Question

I have an NSMenuItem with a bunch of items in it, however... the list just doesn't get enabled.

What I mean:
List

This is my code:

- (void)didFetchNewList:(NSArray *)list
{
    NSArray *smallList = [list subarrayWithRange:NSMakeRange(0, 10)];

    NSMenu *menu = [[NSMenu alloc] initWithTitle:@""];

    for (NSDictionary *dict in smallList)
    {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"MMM dd @ HH:mm:ss"];

        NSMenuItem *soMenuItem = [[NSMenuItem alloc] initWithTitle:
                  [dateFormatter stringFromDate:[dict objectForKey:@"date"]]
                                                            action:nil
                                                     keyEquivalent:@""];
        [soMenuItem setEnabled:YES];

        [menu addItem:soMenuItem];        
    }

    [menu addItem:[NSMenuItem separatorItem]];

    NSMenuItem *soMenuItem =  [[NSMenuItem alloc]
                     initWithTitle:@"Settings" action:nil keyEquivalent:@"S"];
    [soMenuItem setEnabled:YES];
    [menu addItem:soMenuItem];

    [statusItem setMenu:menu];
    [statusItem setEnabled:YES];

}

I am setting everything as enabled, yet it is still disabled. How can I solve this?

Was it helpful?

Solution

When you create an NSMenuItem your item will have to have a valid target and a valid selector. This means the target cannot be nil, and has to respond to the passed selector. Keep in mind that in this case a NULL selector will not enable the menu item.

NSMenu *myMenu;
NSMenuItem *myItem;

myMenu = [[NSMenu alloc] initWithTitle:@""];
myItem = [[NSMenuItem alloc] initWithTitle:@"Test" action:@selector(validSelector:) keyEquivalent:@""];
[myItem setTarget:myTarget];
[myMenu addItem:myItem];
// Do anything you like
[myMenu release];
[myItem release];

EDIT: I saw you're calling -[NSMenuItem setEnabled:] with YESafter you create the menu item. This not necessary, as they will be enabled by default.

EDIT 2: As NSGod pointed out (see comment below) the target can be nil. In that case the first responder of your application will receive the passed method. That is, as long as the first responder has that method implemented. (edit 3) However if this is not the case, the method will be sent to the next responder in the responder chain. This continues until either a responder is found that responds to the selector or there are no responders left to examine. When no responder is found you menu item won't get enabled.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top