我正在 Mac 上使用 cmake 创建一个简单的 C++ 应用程序。C++ 源代码文件中有一个 main,用于创建 C++ 类。在这个类中,我分配了目标 C 对象,将其自身添加到 NSNotificationCenter 中的观察者。而且我没有收到这些通知。有一个代码:
通知.h
class LaunchNotification {
public:
LaunchNotification();
virtual ~LaunchNotification();
void StartNotifications();
void StopNotifications();
private:
void *monitor;
};
通知.mm
@interface Monitor : NSObject
-(id) init;
-(void) appLaunchedNotification :(NSNotification *) notification;
-(void) appTerminatedNotification :(NSNotification *) notification;
@end
@implementation Monitor
- (id) init
{
self = [super init];
if (self)
{
count = 0;
NSNotificationCenter *notCenter = [[NSWorkspace sharedWorkspace] notificationCenter];
[notCenter addObserver : self
selector:@selector(appLaunchedNotification:)
name:NSWorkspaceDidLaunchApplicationNotification
object:nil];
[notCenter addObserver : self
selector:@selector(appTerminatedNotification:)
name:NSWorkspaceDidTerminateApplicationNotification
object:nil];
}
return self;
}
- (void) appLaunchedNotification : (NSNotification *) notification
{
NSString *path = [[notification userInfo]objectForKey: @"NSApplicationPath"];
}
- (void) appTerminatedNotification : (NSNotification *) notification
{
NSString *path = [[notification userInfo]objectForKey: @"NSApplicationPath"];
}
- (void) dealloc
{
NSNotificationCenter *notCenter = [[NSWorkspace sharedWorkspace] notificationCenter];
[notCenter removeObserver : self];
[super dealloc];
}
@end
LaunchNotification::LaunchNotification() : monitor(NULL)
{}
LaunchNotification::~LaunchNotification()
{
StopNotifications();
}
void LaunchNotification::StartNotifications()
{
if (NULL == monitor)
{
monitor = [[Monitor alloc] init];
}
}
void LaunchNotification::StopNotifications()
{
if (NULL != monitor)
{
[(id)monitor release];
}
}