【问题标题】:NSNotification not being received in another classNSNotification 未在另一个类中收到
【发布时间】:2022-10-02 04:08:02
【问题描述】:

我正在尝试从一个班级向另一个班级发送通知,但 notificationReceived 永远不会被调用。

应用委托:

#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

经理:

#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

观察员:

#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

【问题讨论】:

  • TestManagerTestObserver 发布后开始观察。
  • 是的,我在示例中删除了我的计时器。我刚刚编辑了它,所以它也有一个计时器,就像我的实际用例@Willeke
  • 我试过你的代码,它对我有用。 TestManager 是否已解除分配?
  • 在我的 AppDelegate 中,只需在 applicationDidFinishLaunching 中使用 [[TestManager alloc] init];。我还在每个方法中都记录了一个日志,它们都被调用了,除了notificationReceived。 @Willeke
  • 请发布一个完整的代码示例来演示该问题。

标签: objective-c macos nsnotificationcenter


【解决方案1】:

TestManagerTestObserver 都必须是属性/ivar,否则其中任何一个都被过早地释放。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多