2012-11-09 169 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