Search code examples
objective-cmacosnsnotificationcenter

NSNotification not being received in another class


I'm trying to send a notification from one class to another, but notificationReceived never gets called.

AppDelegate:

#import <Cocoa/Cocoa.h>
#import "TestManager.h"

@interface AppDelegate : NSObject <NSApplicationDelegate>
@end

------------------------------

#import "AppDelegate.h"

@interface AppDelegate ()
@end

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    NSLog(@"did finish launching");
    [[TestManager alloc] init];
}
@end

Manager:

#import <AppKit/AppKit.h>
#import "TestObserver.h"

@interface TestManager : NSObject
@end

------------------------------

#import "TestManager.h"

@implementation TestManager
- (instancetype)init {
    self = [super init];

    if (self) {
        NSLog(@"manager init");
        [[TestObserver alloc] init];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationReceived) name:@"testnotification" object:nil];
    }

    return self;
}

- (void)notificationReceived {
    NSLog(@"notification received");
}
@end

Observer:

#import <AppKit/AppKit.h>

@interface TestObserver : NSObject
@end

------------------------------

#import "TestObserver.h"

@implementation TestObserver
- (instancetype)init {
    self = [super init];

    if (self) {
        NSLog(@"observer init");
        [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(sendNotification) userInfo:nil repeats:YES];
    }

    return self;
}

- (void)sendNotification {
    NSLog(@"observer post");
    [[NSNotificationCenter defaultCenter] postNotificationName:@"testnotification" object:nil];
}
@end

Solution

  • Both TestManager and TestObserver need to be a property/ivar, or else either one is deallocated too early.