2013-06-28 39 views
0

我在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]; 
    } 
} 
+0

你的應用程序(NSRunLoop)中是否有「運行循環」? –

+0

據我所知,它不需要它(「每個NSThread對象,包括應用程序的主線程,都會根據需要爲它自動創建一個NSRunLoop對象。」) – Ation

+0

但是,您可能必須「運行」循環。有關示例,請參閱' - [NSRunLoop run]'的文檔。 Cocoa和iOS應用程序會自動執行此操作,但不會執行命令行工具。 –

回答

1

你需要一個運行循環,否則,NSWorkspace沒有這樣的機制,以獲得您的應用程序的線程的控制爲了發佈通知。

雖然文檔說run run循環是自動創建的,但它們是而不是自動執行。想想看:線程如何同時運行代碼並在運行循環中運行代碼?

,你需要,而你正在監視的通知中心不需要做任何任務,在runloop事件的背景下完成的如在NSTimer事件上,或者您需要一個單獨的線程用於其他內容。

+0

我可以不在主線程中處理此通知嗎? – Ation

+1

@Ation通知在引發它們的線程中處理。如果通知在主線程中引發,它將在主線程中處理。還有其他一些方法可以在另一個線程中使事情發生,例如'-performSelector:onThread:withObject:waitUntilDone:'或'-performSelector:inBackgroundWithObject:'你也可以使用NSOperations或GCD。查看[併發指南](http://developer.apple.com/library/ios/#documentation/General/Conceptual/ConcurrencyProgrammingGuide/Introduction/Introduction.html#//apple_ref/doc/uid/TP40008091)。 – JeremyP

相關問題