UIApplicationDidBecomeActiveNotification没有调用

时间:2015-09-29 11:05:05

标签: ios nsnotificationcenter

我正在使用下面的代码来检测我的viewcontroller从后台显示的东西:

    - (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
// some other codes
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(backsFromBackground:) name:UIApplicationDidBecomeActiveNotification object:self];

}

    - (void) backsFromBackground:(NSNotification *) notification
{
    //Do something

}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self  name:UIApplicationDidBecomeActiveNotification object:self];

}

但是观察者没有调用和方法backsFromBackground:没有调用。有人有任何想法吗?

2 个答案:

答案 0 :(得分:3)

请尝试一下:在您的情况下,notificationSender必须为nil

- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    // some other codes
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(backsFromBackground:) name:UIApplicationDidBecomeActiveNotification object:nil];
}

来自Apple Documentation:最后一个参数是您的notificationSender

  

观察者想要接收通知的对象;那是,   只有此发件人发送的通知才会传递给观察者。

     

如果您通过nil,通知中心不会使用通知   发送者决定是否将其传递给观察者。

答案 1 :(得分:2)

更改此行

[[NSNotificationCenter defaultCenter] addObserver:self
  selector:@selector(backsFromBackground:)
  name:UIApplicationDidBecomeActiveNotification
  object:self];

[[NSNotificationCenter defaultCenter] addObserver:self 
  selector:@selector(backsFromBackground:)
  name:UIApplicationDidBecomeActiveNotification
  object:nil];

object订阅中的最后一个NSNotificationCenter参数是通知发件人,您要观察的对象。更改不是来自您的视图控制器(self),它们来自UIApplication

您可以传递[UIApplication sharedApplication],但由于UIApplication只有object个实例,因此您可以将removeObserver参数保留为nil。

您也希望在{{1}}代码中也这样做。

相关问题