Question

I need to add multiple status menuitems programmatically. I have never used NSStatusItem before. The following is what I have.

- (void)showStatus {
    for (NSInteger i4 = 0; i4 < alertArray4.count; i4++) {
        NSString *person = [[alertArray4 objectAtIndex:i4] objectForKey:key4e];
        NSString *imagepath = [[alertArray4 objectAtIndex:i4] objectForKey:key4f];
        NSString *nextDOB = [[alertArray4 objectAtIndex:i4] objectForKey:key4h];
        NSImage *personimage;
            if ([imagepath isEqualToString:@"0"]) {
                personimage = [self imageResize:[NSImage imageNamed:@"userNone"] newSize:NSMakeSize(16.0f,16.0f)];
            }
            else {
                personimage = [self imageResize:[NSImage imageNamed:@"userOne"] newSize:NSMakeSize(16.0f,16.0f)];
            }   
            NSString *menuTitle = [NSString stringWithFormat:@"%@ in %@ days",person,nextDOB];
            NSMenuItem *menuItem = [[NSMenuItem alloc] initWithTitle:menuTitle action:@selector(statusItemClicked:) keyEquivalent:@""];
            [menuItem setImage:personimage];
        }
    statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSVariableStatusItemLength];
    statusImage = [NSImage imageNamed:@"appIcon16"];
    [statusItem setImage:statusImage];
    [statusItem setMenu:statusMenu];
    [statusItem setTitle:alertCount.stringValue];
}

- (void)statusItemClicked:(NSString *)num {
    NSLog(@"Hello");
}

And the application posts a status menu with the number of items = i4. What I don't understand is how to pass a variable to statusItemClicked so that the application will know which menuitem the user has selected. So how can I send a variable (i4) to statusItemClicked? If you use performSelectorInBackground, you can append a variable to withObject. I guess I can't do that in this case.

Thank you for your help.

Was it helpful?

Solution

I don't know exactly how it works. Anyway, I've ended up with the following, which serves me to my satisfaction.

- (void)showStatus {
for (NSInteger i4 = 0; i4 < alertArray4.count; i4++) {
    ...
    NSString *num4 = [NSString stringWithFormat:@"%li",(long)i4];
    NSString *menuTitle = [NSString stringWithFormat:@"%@ in %@ days",person,nextDOB];
    NSMenuItem *menuItem = [[NSMenuItem alloc] initWithTitle:menuTitle action:@selector(statusItemClicked:) keyEquivalent:@""];
    [menuItem setTarget:self];
    [menuItem setRepresentedObject:num4];
}
statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSVariableStatusItemLength];
statusImage = [NSImage imageNamed:@"appIcon16"];
[statusItem setImage:statusImage];
[statusItem setMenu:statusMenu];
[statusItem setTitle:alertCount.stringValue];
}

- (void)statusItemClicked:(id)sender {
    id selectedItem = [sender representedObject];
    NSLog(@"%@",selectedItem);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top