Search code examples
objective-ccocoansnotificationcenternsnotifications

Cocoa Posting an NSNotification from a subclass within a subclass


I am having an issue with receiving an NSNotification that is being sent from an NSButton that has been subclassed to detect double clicks. Which itself is used within a subclass of NSView.

When I post the notification to the default notification center it never arrives in my appDelegate where I am listening for it.

Here is my NSButton subclass:

#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

Listening in my AppDelegate applicationDidFinishLaunching method:

//Notification for Double tap notification
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(doubleTapAction:)
                                             name:@"doubleClickButtonNotification"
                                           object:self];

The notification never arrives and doubleTapAction: is never called.

Please could someone point me in the correct direction as it is melting my brain...

Many Thanks in advance

Ben


Solution

  • First of all: User events (as a mouse down) are always delivered on the main thread. Therefore you do not need the -performSelectorOnMainThread:….

    To your Q: Likely you misunderstood the object parameter. Why do you set it to nil when posting a notification and set it to self for adding the observer? Since nil is not $anySelf that does not match. You can set this parameter to nil when you add the observer to get notifications of all senders. So simply do it the other way round. (Setting object to something useful when posting the notification and to nilwhen adding the observer.)