2013-03-06 22 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