当用户退出应用程序ios时调用viewWillDisappear

Ada*_*aya 6 ios

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

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

有没有办法viewWillDisappear在用户按下主页按钮后立即为该视图运行该方法?

dig*_*lls 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

}
Run Code Online (Sandbox Code Playgroud)