2010-07-29 142 views
4

我使用UIDeviceOrientationDidChangeNotification時遇到了一些問題。在我離開某個ViewController(viewWillDisappear:方法被調用)後,設備不會停止發送通知。UIDeviceOrientationDidChangeNotification不會停止

這意味着,在將另一個ViewController放在堆棧頂端並旋轉設備後,此處的ViewController的receiversRotate:方法將被調用,而我不想要。

我在這裏也找不到文檔和其他主題中的內容。如果有人能夠幫助,這將是非常棒的。

我的情況是這樣的:

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receivedRotate:) name:UIDeviceOrientationDidChangeNotification object:nil]; 

    // other things... 
} 

這裏viewWillAppear中:方法

- (void)viewWillAppear:(BOOL)animated { 

    [super viewWillAppear:animated]; 
    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications]; 
} 

和最後的viewWillDisappear:方法

- (void)viewWillDisappear:(BOOL)animated { 
    [super viewWillDisappear:animated]; 
    [[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications]; 
} 

提前感謝!

回答

12

-viewWillDisappear:,取出觀察:

[[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil]; 
+0

謝謝您的回答。它與以下解決方案一起工作:我添加了代碼以移除viewWillDisappear中的觀察者:但必須在viewWillAppear中添加觀察者:因爲第二次顯示視圖時,不會添加觀察者。 但是,我還是不明白beginGeneratingDeviceOrientationNotifications和endGeneratingDeviceOrientationNotifications的含義。在我的應用程序中,兩者都不會影響通知的發佈。通知總是被解僱?!?! – schaechtele 2010-07-29 11:42:30

+0

所有類型的通知都會在您的應用運行時觸發,包括針對方向更改的通知。但是,除非一個類(z.B.視圖控制器)已經註冊來偵聽這些通知,否則該類將不會「聽到」通知,也不會對其執行操作。如何定製類的行爲,以及如何指定它們如何響應各種系統級通知,這取決於您。 – 2010-12-12 22:42:30

+0

@AlexReynolds:我認爲你不瞭解schaechtele的評論。 beginGeneratingDeviceNotifications的文檔說,除非您調用此方法,否則不會生成關於設備方向更改的事件,但我也觀察到它在不調用此方法的情況下生成通知。我想這是一個系統範圍的事情,如果任何其他應用程序已打開方向通知,那麼你也將得到它們,而不會調用beginGeneratingDeviceOrientationNotifications。 – hktegner 2012-05-23 18:16:38