NSNotificationCenter addObserverForName 的釋放

  • 先讓我們來看看正確的姿勢, 一定要在想要釋放內存前把持有的對象釋放掉, 千萬不要在dealloc 裏面寫, 根本沒有機會走到dealloc, 這個跟NSTime 類類似的道理,[self.timer invalidate]; 要提前處理掉
@property (nonatomic, strong) id observer;

- (void) viewDidLoad {
  self.observer = [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidEnterBackgroundNotification
                                                      object:nil 
                                                      queue:[NSOperationQueue mainQueue]
                                                  usingBlock:^(NSNotification *note) {
                                                      NSLog("hello");
                                                  }];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];    
    if (self.observer) {
        [[NSNotificationCenter defaultCenter] removeObserver:self.observer];
        self.observer = nil;
    }
}
- (void)dealloc
{
    NSLog(@"MTC_dealloc OK");
}

下面這個兄弟寫錯了 , 永遠不會釋放掉這個UIViewControl了……
http://www.jianshu.com/p/1788d15c570b

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章