2011-06-24 54 views
4

什麼時候應該添加和刪除UIApplication通知的觀察者?我應該何時添加/刪除UIApplication Notifications的觀察者?

- (void)viewWillAppear:(BOOL)animated { 
    [super viewWillAppear:animated]; 

    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; 
    [nc addObserver:self selector:@selector(saveState) name:UIApplicationWillResignActiveNotification object:nil]; 
    [nc addObserver:self selector:@selector(loadState) name:UIApplicationWillEnterForegroundNotification object:nil]; 
} 

- (void)viewWillDisappear:(BOOL)animated { 
    [super viewWillDisappear:animated]; 
    [self.navigationController setNavigationBarHidden:YES animated:animated]; 

    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; 
    [nc removeObserver:self name:UIApplicationWillResignActiveNotification object:nil]; 
    [nc removeObserver:self name:UIApplicationWillEnterForegroundNotification object:nil]; 
} 

這是壞?當視圖在屏幕上時,我只對通知感興趣。如果在viewWillDisappear:方法中刪除UIApplicationWillEnterForegroundNotification會有什麼問題嗎?我在想事情發生的順序......?

回答

1

- (id)init{}或其他匹配的初始值設定項中使用它,而使用- (void)dealloc{}。舉例來說,在viewWillAppear和viewWillDisappear中添加和刪除觀察者會不必要地多次執行此操作。

對於使用ARC的項目,仍然可以實現dealloc方法。就像您使用手動保留/發佈項目一樣,不要撥打[super dealloc]。事實上,編譯器不會讓你。