当用户退出应用程序时调用viewWillDisappear方法(iOS)

6
我有一个应用程序,它在其中一个类的viewWillDisappear方法中存储值。例如,在viewWillAppear方法中存储数据和时间,并在viewWillDisappear方法中再次存储相同的数据和时间,以便我能够比较时间差异并记录下来。
然而,如果用户按设备上的主页按钮,则不会运行viewWillDisappear代码。我尝试在AppDelegateapplicationDidEnterBackground中调用此特定方法,但这会存储错误的信息,因为实际上没有运行viewWillDisappear方法。 我还尝试将它们存储在NSUserDefaults中,但是由于viewWillDisappear方法未运行,因此存储了错误的值。
是否有一种方法可以使viewWillDisappear方法在用户按下主页按钮时立即运行该视图?
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

}

1
viewWillAppear:viewWillDisappear:两者都必须在某个时刻调用super。 - Valeriy Van

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接