2013-03-06 23 views
1

如何以乾淨的方式在塊中實例化2個BOOL變量?正確使用notificationCenter addObserverForName與塊

作爲後續,它的工作,但我有「捕獲‘自我’強烈該塊很可能會導致保留週期」,這顯然是不好的......

[notificationCenter addObserverForName:UIApplicationDidEnterBackgroundNotification 
            object:nil 
            queue:mainQueue usingBlock:^(NSNotification *note) { 
             isApplicationOnForegroundMode = NO; 
             isApplicationOnBackgroundMode = YES; 
            } ]; 


    [notificationCenter addObserverForName:UIApplicationDidBecomeActiveNotification 
            object:nil 
            queue:mainQueue usingBlock:^(NSNotification *note) { 
             isApplicationOnForegroundMode = YES; 
             isApplicationOnBackgroundMode = NO; 
            } ]; 

回答

3

我猜想isApplicationOnForegroundModeisApplicationOnBackgroundMode是ivars。

您需要添加幾個ivars或屬性來跟蹤觀察塊,以便將其移除。我將調用那些屬性爲backgroundObserver和activeObserver的id

更新您的代碼:

__unsafe_unretained <<self's class>> *this = self; // or __weak, on iOS 5+. 

self.backgroundObserver = [notificationCenter 
          addObserverForName:UIApplicationDidEnterBackgroundNotification 
             object:nil 
              queue:mainQueue 
            usingBlock:^(NSNotification *note) { 
             this->isApplicationOnForegroundMode = NO; 
             // or: this.isApplicationOnForegroundMode = YES, if you have a property declared 
             this->isApplicationOnBackgroundMode = YES; 
            } ]; 


self.activeObserver = [notificationCenter 
         addObserverForName:UIApplicationDidBecomeActiveNotification 
            object:nil 
             queue:mainQueue usingBlock:^(NSNotification *note) { 
              this->isApplicationOnForegroundMode = YES; 
              this->isApplicationOnBackgroundMode = NO; 
             } ]; 

您還需要確保你叫

[[NSNotificationCenter defaultCenter] removeObserver:self.backgroundObserver]; 
[[NSNotificationCenter defaultCenter] removeObserver:self.activeObserver]; 
-dealloc

+0

我想新的基於塊的通知觀察者返回一個id對象,應該用於刪除觀察者。我不知道他們是否與自己一樣。他們? – John 2013-03-06 04:56:02

+0

不需要。「object」參數是過濾通知傳遞的一種機制,通常表示「我只想在通過對象Y發送時通知X」。您可以通過僅匹配觀察者,觀察者和通知名稱,觀察者,通知名稱和觀察對象來移除觀察者,但在dealloc中,上面的表單最簡單並且最有效:它表示「將我從所有通知中移除」。 – 2013-03-06 05:00:38

+0

這就像在JavaScript中,我喜歡thx! – 2013-03-06 05:03:17