我正在尝试在FinderSync扩展中实现一个简单的上下文菜单。
我使用一些示例构建了以下内容,我的问题是单击菜单项时从不调用回调。
源代码:
ContextMenuHelper.h
#import <Foundation/Foundation.h>
#include "FinderSync.h"
@interface ContextMenuHelper : NSObject
+ (NSMenu *)buildMenu;
@end
ContextMenuHelper.m
#import "ContextMenuHelper.h"
#define SharedContextMenuTarget [ContextMenuTarget sharedInstance]
@interface ContextMenuTarget : NSObject
+ (ContextMenuTarget *) sharedInstance;
@end
@implementation ContextMenuTarget
- (void) callback : (id)sender {
NSLog(@"Called back!!!");
}
+ (ContextMenuTarget *) sharedInstance
{
static ContextMenuTarget *sharedContextMenuTarget = nil;
@synchronized(self)
{
if (!sharedContextMenuTarget)
sharedContextMenuTarget = [[ContextMenuTarget alloc] init];
return sharedContextMenuTarget;
}
}
@end
@implementation ContextMenuHelper
+ (NSMenu *)buildMenu
{
ContextMenuTarget *contextMenuTarget = SharedContextMenuTarget;
NSMenu *mySubmenu = [[NSMenu alloc] initWithTitle:@""];
NSMenuItem *newMenu = [[NSMenuItem alloc] initWithTitle:@"hello"
action:@selector(callback:)
keyEquivalent:@""];
[newMenu setTarget:contextMenuTarget];
[mySubmenu addItem:newMenu];
return mySubmenu;
}
@end
MyFinderSync.m
...
- (NSMenu *)menuForMenuKind:(FIMenuKind)whichMenu {
NSMenu *myContextMenu = [[NSMenu alloc] initWithTitle:@""];
@try
{
if(whichMenu != FIMenuKindContextualMenuForItems) {
return myContextMenu;
}
myContextMenu = [ContextMenuHelper buildMenu];
}
@catch (NSException *ex)
{
}
return myContextMenu;
}
...
答案 0 :(得分:2)
显然,只有当目标是FinderSync
的实例时,回调才会起作用。找不到任何支持这一理论的文档,但解决问题的唯一方法是将上下文菜单代码移动到 MyFinderSync.m :
...
- (NSMenu *)menuForMenuKind:(FIMenuKind)whichMenu {
NSMenu *myContextMenu = [[NSMenu alloc] initWithTitle:@""];
@try
{
if(whichMenu != FIMenuKindContextualMenuForItems) {
return myContextMenu;
}
myContextMenu = [self buildMenu];
}
@catch (NSException *ex)
{
}
return myContextMenu;
}
- (NSMenu *)buildMenu
{
NSMenu *mySubmenu = [[NSMenu alloc] initWithTitle:@""];
NSMenuItem *newMenu = [[NSMenuItem alloc] initWithTitle:@"hello"
action:@selector(callback:)
keyEquivalent:@""];
[newMenu setTarget:self];
[mySubmenu addItem:newMenu];
return mySubmenu;
}
- (void) callback : (id)sender {
NSLog(@"Called back!!!");
}
...