我在Mac上用cmake創建了一個簡單的C++應用程序。 在C++源代碼文件中有一個主要的,它創建C++類。在這個類的內部,我分配了一個客觀的C對象,它將自己添加到NSNotificationCenter中的觀察者中。我沒有收到這些通知。 有一個代碼:從C++程序獲取NSNotificationServer的通知
Notifications.h
class LaunchNotification {
public:
LaunchNotification();
virtual ~LaunchNotification();
void StartNotifications();
void StopNotifications();
private:
void *monitor;
};
Notifications.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];
}
}
你的應用程序(NSRunLoop)中是否有「運行循環」? –
據我所知,它不需要它(「每個NSThread對象,包括應用程序的主線程,都會根據需要爲它自動創建一個NSRunLoop對象。」) – Ation
但是,您可能必須「運行」循環。有關示例,請參閱' - [NSRunLoop run]'的文檔。 Cocoa和iOS應用程序會自動執行此操作,但不會執行命令行工具。 –