通过NSStatusItem的Action传递变量

时间:2013-08-08 09:56:02

标签: objective-c macos osx-mountain-lion nsstatusitem

我需要以编程方式添加多个状态菜单项。我之前从未使用过 NSStatusItem 。以下是我所拥有的。

- (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");
}

应用程序发布一个状态菜单,其中items = i4。我不明白的是如何将变量传递给statusItemClicked,以便应用程序知道用户选择了哪个menuitem。那么如何将变量( i4 )发送到statusItemClicked?如果使用 performSelectorInBackground ,则可以将变量附加到 withObject 。我猜我不能这样做。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我不确切知道它是如何工作的。无论如何,我最终得到了以下内容,这让我满意。

- (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);
}