Where to put selector of NSMenuItem

2019-05-28 22:20发布

I try to understand a few things in Cocoa but I got stuck on one thing. I'm following Minimalistic Cocoa Programming, there it is a NSMenuItem responsible for terminating the app. Now, I would like to create another NSMenuItem, with a shortcut, that when pressed, it NSLog-s something. But I don't know where should I put the implementation of said selector? Should I subclass the whole NSApplication? Should I setDelegate to some NSObject instance, acting as a controller?

1条回答
神经病院院长
2楼-- · 2019-05-28 22:25

You need to create a class that can be used as the target of the menu item. Something like this:

@interface Tester : NSObject
@end
@implementation Tester
- (void)logTest:(id)sender
{
    NSLog(@"Test");
}
@end

Then set it as the target:

id testMenuItem = [[[NSMenuItem alloc] initWithTitle:@"Log Test" action:@selector(logTest:) keyEquivalent:@"l"] autorelease];
id tester = [[[Tester alloc] init] autorelease];
[testMenuItem setTarget:tester];
查看更多
登录 后发表回答