2012-11-09 130 views

回答

9

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

+0

你有一些例子链接,因为我从来没有用户UIApplicationWillEnter ForegroundNotification? – CroiOS

+3

http://stackoverflow.com/questions/3535907/how-to-tell-when-controller-has-resumed-from-background – Cyrille

+0

非常好,它的工作原理。非常感谢你。 – CroiOS

0

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

7

您HomeViewController

- (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]; 
} 

创建viewDidLoad方法这样如果你的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]; 
} 

或者你可以使用块:

[[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationWillEnterForegroundNotification 
                object:nil 
                queue:[NSOperationQueue mainQueue] 
               usingBlock:^(NSNotification *note) { 
                [[self tableView] reloadData]; 
               }]; 
+0

不要忘记删除dealloc上的观察者! – Cyrille

+0

的确是Cyrille! – Tieme