Search code examples
cocoansmenu

contextual menu item are not getting activated


I am having a problem. My contextual menu is getting displayed but the menu items are not activated. so my new code for displaying the menu is as follows:

NSMenu *defMenu = [[[NSMenu alloc] initWithTitle:@"default Contextual Menu"] autorelease];

[defMenu insertItemWithTitle:@"Open" action:@selector(openFile) keyEquivalent:@"" atIndex:0];

[defMenu insertItemWithTitle:@"Delete" action:@selector(deleteFile) keyEquivalent:@"" atIndex:1];

return defMenu;

and function declaratons of deleteFile and openFile are as follows:

-(int)openFile;

-(int)deleteFile;

and i am calling my contextual menu as follows:

-(void)doSingleClick 
{

    if([[NSApp currentEvent] modifierFlags] & NSControlKeyMask)
    {

        NSLog(@"control clicked.......");

        [NSMenu popUpContextMenu:[self defaultMenu] withEvent:[NSApp currentEvent] forView:tableView];

        return;
    }

}

my contextual menu items are all shaded and cannot be clicked. Please can you tell where i am going wrong.

Thanks


Solution

  • Your openFile: method takes an int as a parameter. Since insertItemWithTitle:action:withObject:keyEquivalent:atIndex: takes an object, the selector you give it must also take an object.

    You can use NSNumber to wrap your int as an object, and simply change your openFile: method to take an NSNumber rather than an int. Like so:

    [defMenu insertItemWithTitle:@"Open" action:@selector(openFile:) withObject:[NSNumber numberWithInt:5] keyEquivalent:@"" atIndex:0];
    
    - (void)openFile:(NSNumber *)fileNumber {
        int rowClicked = [fileNumber intValue];
        // Do whatever your old method did here
    }
    

    EDIT: To answer your updated question:

    The reason your menu items are disabled is that you've only told them what method name to call. You never told the items on which object instance those methods should actually be called. To fix this, you need to set the items' target:

    NSMenuItem *openItem = [defMenu insertItemWithTitle:@"Open" action:@selector(openFile:) withObject:[NSNumber numberWithInt:5] keyEquivalent:@"" atIndex:0];
    [openItem setTarget:self];
    

    And so forth for each item you've got.