正确使用notificationCenter addObserverForName with blocks

时间:2013-03-06 04:29:48

标签: objective-c nsnotificationcenter

如何以干净的方式在块中实例化2个BOOL变量?

如下所示,它正在发挥作用,但我在这个区块中“强烈捕捉'自我'可能会导致保留周期”,这显然不是很好......

    [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;
                                     } ];

1 个答案:

答案 0 :(得分:3)

我认为isApplicationOnForegroundModeisApplicationOnBackgroundMode是ivars。

您需要添加几个ivars或属性来跟踪观察区块,以便您可以删除它们。我将称之为id属性backgroundObserver和activeObserver。

将您的代码更新为:

__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中的