在自定义UITableViewCell中将addObserver添加到NSNotificationcenter的位置?

时间:2013-07-12 06:25:30

标签: ios uitableview nsnotificationcenter nsnotification

在我的UITableViewCell中,我有一个方法initNotification,它由cellForRowAtIndexPath中的TableViewController调用,其中创建了TableCells。

我的问题是,每次重新加载此视图时,都会再次调用initNotification方法,因此当出现Notification时,NotificationHandle会被调用x次!

我尝试删除Observer,然后再次添加:

-(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总是重新初始化Cell。

是否有正确的方法从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;
}

由于

1 个答案:

答案 0 :(得分:11)

一般来说,细胞不应该观察任何东西。控制器应该观察变化并将更新的信息推送到单元格上。

在添加观察者之前调用removeObserver:应该有效。如果您要在prepareForReusetableView:didEndDisplayingCell:forRowAtIndexPath:中执行任何操作来重置单元格,那么这将是您使用的代码。你需要看一下你如何测试它是如何工作的以及你如何重复使用单元格。

相关问题