objective-c - Cocoa 从子类中的子类发布 NSNotification

标签 objective-c cocoa nsnotificationcenter nsnotifications

我在接收从 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/

相关文章:

objective-c - 在设备上运行时找不到图像,但在模拟器上运行时可以找到它

objective-c - 具有核心数据和表格 View 的 Apple 模板 iOS 文件

iphone - 从 UITabBarController 中消除 UIImagePickerController

ios - 在后台通过 iCloud 同步本地通知

ios - 如何找出 NSManagedObjectContextObjectsDidChange 关注的 MOC

ios - 捕获 NSNotification postNotification 的错误

ios - 在后台线程中创建 View Controller

ios - 基于在第一个 View Controller 中按下的按钮,xcode 在第二个 View Controller 中打开 url

objective-c - 类似 nswindow 级别的 growl 通知

macos - NSPopover 内的 NSView : Converting Coordinates