2013-07-12 36 views
3

在我的UITableViewCell中,我有一個方法initNotification,它由創建TableCells的cellForRowAtIndexPath中的TableViewController調用。在自定義UITableViewCell中將Observer添加到NSNotificationcenter的位置?

我的問題是,每當這個視圖重新加載,initNotification方法再次被調用,所以當Notification出現時,NotificationHandle被稱爲x-times!

我試圖與重新加入之前刪除觀察報:

-(void) initNotification{ 
    [[NSNotificationCenter defaultCenter] removeObserver:self]; 

    [[NSNotificationCenter defaultCenter] 
    addObserver:self 
    selector:@selector(handleNotificationOnOff:) 
    name:[[NSString alloc] initWithFormat:@"%@",[self.light beckhoffOnOff]] 
    object:nil]; 
} 

但是這也不能工作。 問題是,我不能使用bool-flag或類似的東西,因爲單元總是被ViewController重新初始化。

是否有正確的方式從NotificationCenter中刪除NotificationHandle?

編輯:這是我如何創建我的自定義TableViewCells

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UITableViewCell *cell; 
    Light* l = [[staticModel.model getRoomAtIndex:[indexPath section]]getLightAtIndex:[indexPath item]]; 
    if([l typ]==ONOFF){ 
     TableCellLight *conof = [tableView dequeueReusableCellWithIdentifier:@"ReuseIDOnOff" forIndexPath:indexPath]; 
     LightOnOff *lonof = (LightOnOff*) l; 
     [[conof label] setText: [lonof bezeichnung]]; 
     conof.light=lonof; 

     [conof initNotification]; 
     cell = conof; 
    } 
    if([l typ]==DIMMER){ 
     TableCellLightDim *cdim = [tableView dequeueReusableCellWithIdentifier:@"ReuseIDDim" forIndexPath:indexPath]; 

     LightDim *ldim= (LightDim*) l; 
     [[cdim label] setText: [ldim bezeichnung]]; 
     [[cdim slider]setValue:[ldim dimVal]]; 
     cdim.light=ldim; 
     [cdim initNotification]; 
     cell = cdim; 
    } 
    if([l typ]==RGB){ 
     TableCellLightRGB *crgb = [tableView dequeueReusableCellWithIdentifier:@"ReuseIDRGB" forIndexPath:indexPath]; 
     LightRGB *lrgb= (LightRGB*) l; 
     [[crgb label] setText: [lrgb bezeichnung]]; 
     crgb.light=lrgb; 
     crgb.owner=self; 
     [crgb initNotification]; 
     cell = crgb; 
    } 

    return cell; 
} 

感謝

回答

11

一般來說小區不應該被任何觀察。控制器應該觀察更改並將更新的信息推送到單元格上。

調用removeObserver:在添加觀察者之前應該工作。如果您要在prepareForReusetableView:didEndDisplayingCell:forRowAtIndexPath:中執行任何操作來重置單元格,那將是您使用的代碼。你需要看看你如何測試它不能正常工作以及如何重用單元。

+0

感謝您的回覆! 我已經想出了爲什麼removeObserver:不起作用,因爲自我不再一樣了,每當TableView重新加載(以及單元格)時,我都會得到每個單元格的新實例。有沒有辦法強制細胞去分配? – user2071938

+0

如果您不重複使用它們應該釋放的單元格(如在中,您沒有重用標識符)。但這並不理想。 – Wain

+0

我有一個重用標識符,但爲什麼結束了同一個單元的許多實例呢? – user2071938

相關問題