6

我有一个应用程序将值存储在viewWillDisappear我的一个类中的方法中。例如,我将数据和时间存储在viewWillAppear方法中,并且在方法中再次存储相同的数据和时间,viewWillDisappear以便我能够比较时间差并将其记录下来。

但是,如果用户按下设备上的主页按钮,则viewWillDisappear代码不会运行。我尝试在AppDelegate's中调用此特定方法applicationDidEnterBackground,但这会存储错误信息,因为该viewWillDisappear方法实际上并未运行。我也尝试将它们存储在 中NSUserDefaults,但同样,由于该viewWillDisappear方法未运行,因此存储了错误的值。

viewWillDisappear一旦用户按下他们的主页按钮,有没有办法让该方法为该视图运行?

4

1 回答 1

8

在 viewWillAppear 注册此通知...

-(void)viewWillAppear:(BOOL)animated {

[[NSNotificationCenter defaultCenter] addObserver: self
                                         selector: @selector(appEnteredBackground:)
                                             name: UIApplicationDidEnterBackgroundNotification
                                           object: nil];

}

-(void)viewWillDisappear:(BOOL)animated {

    [[NSNotificationCenter defaultCenter] removeObserver:self];

}

-(void)appEnteredBackground:(NSNotification *)appEnteredBackgroundNotification {

    //do your thing

}
于 2013-11-07T15:11:32.080 回答