1

如何以干净的方式在一个块中实例化 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;
                                     } ];
4

1 回答 1

3

我认为是isApplicationOnForegroundModeivars isApplicationOnBackgroundMode

您需要添加几个 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.

于 2013-03-06T04:42:57.773 回答