2012-03-11 87 views
0

我將按鈕添加到UITableViewHeader,但獲得觀察員沒有釋放之前刪除控制檯消息:觀察員未刪除

一個實例類的UIButton的0x4b4750被釋放,而鍵值 觀察員仍然註冊它

這是可以理解的,所以我想將其刪除,但不確定的去了解這一點的最好辦法。唯一值得思考的是將它們全部添加到數組中,然後在dealloc中循環遍歷它們,並刪除創建它們的類作爲觀察者。雖然我不完全確定哪些參數傳遞到[[NSNotificationCenter defaultCenter] removeObserver。在每個標題視圖中有三個不同的按鈕,每個按鈕發出不同的回調。這是否意味着我需要三個數組,然後使用removeTarget

回答

0

docs

重要通知中心不保留其觀察員, 因此,你必須確保註銷觀察員(使用 removeObserver:或removeObserver:名稱:對象:)他們是前 解除分配。 (如果你不這樣做,你會如果 中心將消息發送到釋放對象生成運行時錯誤。)

如果你的子類的按鈕,那麼你可以發佈一條消息給所有的觀察者的可觀察的UIButton即將出現。

[[NSNotificationCenter defaultCenter] postNotificationName:@"UIButton_dealloc" object:self]; 

或者,在分配的按鈕,一旦按鈕將被刪除,你可以在類:

[[NSNotificationCenter defaultCenter] postNotificationName:@"UIButton_dealloc" object:theButton]; 

和觀察的對象,在這兩種情況下,將做到這一點:

// The special event 
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doSomething:) name:@"UIButton_event" object:theButton]; 
// The dealloc 
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stopObserving:) name:@"UIButton_dealloc" object:theButton]; 
.... 
-(void) stopObserving:(NSNotification*)notif { 
    if ([name isEqualToString:@"UIButton_dealloc"]) { 
     [[NSNotificationCenter defaultCenter] removeObserver:self name:@"UIButton_event" object:object]; 
    } 
} 

但是,在UIButton的情況下,這是一個有點令人費解的例子,但可以用於其他情況。

+0

我不知道這將如何映射到我目前使用的控件事件。要添加觀察者,我目前使用'addTarget',所以如果我'addTarget'我不需要也'removeTarget'?無論哪種方式,是一個數組來跟蹤最佳方法? – Echilon 2012-03-11 14:10:51

+0

我認爲它會,請參閱http://cocoawithlove.com/2008/06/five-approaches-to-listening-observing.html觀察員信息 – 2012-03-11 15:51:51

+0

這仍然沒有真正回答如何刪除添加到buttn的目標對於UIControlEvent。我將作爲參數傳遞給'removeObserver'的是什麼? – Echilon 2012-03-12 11:51:58