6

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

用户进入 applicationWillEnterForeground 后如何刷新视图?

我想完成召回例如 HomeViewController。

我在 HomeViewController 中有更新功能,我想在用户进入时调用更新功能并重新加载表数据。

4

3 回答 3

9

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

于 2012-11-09T14:30:49.977 回答
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];
}

如果你的 ViewController 是一个 tableViewController 你也可以直接调用 reload data 函数:

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

}
- (void) dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
}

或者你可以使用一个块:

[[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationWillEnterForegroundNotification
                                                  object:nil
                                                   queue:[NSOperationQueue mainQueue]
                                              usingBlock:^(NSNotification *note) {
                                                  [[self tableView] reloadData];
                                              }];
于 2012-11-09T14:40:11.517 回答
0

您可以在应用程序委托类中声明一个指向 HomeViewController 对象的属性。然后您可以在 applicationWillEnterForeground 中调用您的更新函数。

于 2012-11-09T14:30:45.873 回答