我在接收从 NSButton 发送的 NSNotification 时遇到问题,该 NSButton 已被子类化以检测双击。它本身在 NSView 的子类中使用。
当我将通知发布到默认通知中心时,它永远不会到达我正在监听的 appDelegate 中。
这是我的 NSButton 子类:
#import "DoubleClickButton.h"
#import "AppDelegate.h"
@implementation DoubleClickButton
- (void)mouseDown:(NSEvent *)theEvent
{
NSInteger clickCount = [theEvent clickCount];
if (2 == clickCount)
{
[self performSelectorOnMainThread:@selector(handleDoubleClickEvent:) withObject:nil waitUntilDone:NO];
}
}
-(void)handleDoubleClickEvent:(NSEvent *)event
{
NSLog(@"DoubleClick");
[[NSNotificationCenter defaultCenter] postNotificationName:@"doubleClickButtonNotification" object:nil];
}
@end
在我的 AppDelegate applicationDidFinishLaunching 方法中监听:
//Notification for Double tap notification
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(doubleTapAction:)
name:@"doubleClickButtonNotification"
object:self];
通知永远不会到达,并且 doubleTapAction: 永远不会被调用。
请有人指出我正确的方向,因为它正在融化我的大脑......
提前非常感谢
本
最佳答案
首先:用户事件(如鼠标按下)始终在主线程上传递。因此,您不需要 -performSelectorOnMainThread:...
。
致您的问题:您可能误解了对象参数。为什么发布通知时设置为nil
,添加观察者时设置为self
?由于 nil
不是不匹配的 $anySelf。当您添加观察者以获取所有发件人的通知时,可以将此参数设置为nil
。所以只需反过来做即可。 (在发布通知时将对象设置为有用的内容,在添加观察者时将对象设置为nil
。)
关于objective-c - Cocoa 从子类中的子类发布 NSNotification,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28897600/