如何在输入applicationWillEnterForeground后刷新View?

iWi*_*ard 6 uiviewcontroller ios

可能重复:
如何判断控制器何时从后台恢复?

用户输入applicationWillEnterForeground后如何刷新View?

我想完成回忆,例如HomeViewController.

我在HomeViewController中有更新功能,我希望当用户进入调用更新功能并重新加载表数据时.

Cyr*_*lle 9

任何类都可以注册UIApplicationWillEnterForegroundNotification,并做出相应的反应.它不是保留给应用程序代理,有助于更好地分离源代码.

  • http://stackoverflow.com/questions/3535907/how-to-tell-when-controller-has-resumed-from-background (3认同)

Tie*_*eme 8

为HomeViewController创建一个这样的viewDidLoad方法

- (void)viewDidLoad
{
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(yourUpdateMethodGoesHere:)
                                                 name:UIApplicationWillEnterForegroundNotification
                                               object:nil];
}

// Don't forget to remove the observer in your dealloc method. 
// Otherwise it will stay retained by the [NSNotificationCenter defaultCenter]...
- (void) dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
}
Run Code Online (Sandbox Code Playgroud)

如果您的ViewController是一个tableViewController,您也可以直接调用重载数据函数:

- (void)viewDidLoad
{
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:[self tableView]
                                             selector:@selector(reloadData)
                                                 name:UIApplicationWillEnterForegroundNotification
                                               object:nil];

}
- (void) dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
}
Run Code Online (Sandbox Code Playgroud)

或者您可以使用块:

[[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationWillEnterForegroundNotification
                                                  object:nil
                                                   queue:[NSOperationQueue mainQueue]
                                              usingBlock:^(NSNotification *note) {
                                                  [[self tableView] reloadData];
                                              }];
Run Code Online (Sandbox Code Playgroud)