在自定义的UITableViewCell中,应该在哪里向NSNotificationCenter添加观察者?

7
在我的UITableViewCell中,我有一个名为initNotification的方法,它由TableViewController在cellForRowAtIndexPath中调用,其中创建TableCells。
我的问题是,每次重新加载此视图时,都会再次调用initNotification方法,因此当通知出现时,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标志或类似的东西,因为单元格始终由ViewController重新初始化。
有没有适当的方法从通知中心删除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个回答

13

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

在添加观察者之前调用removeObserver:应该可以解决问题。如果您要在prepareForReusetableView:didEndDisplayingCell:forRowAtIndexPath:中执行任何重置单元格的操作,那么这就是您需要使用的代码。您需要查看如何测试它未能正常工作以及如何重复使用单元格。


你需要展示代码。你是如何计算单元格实例的数量的?如果你做得正确,那么计数应该略高于屏幕上的单元格数量。 - Wain
每个单元格都有自己的通知,在通知处理程序中,我添加了一个 NSLog(self) 以便我可以计算处理程序被调用的次数(应该只调用一次!)- 我已经将创建单元格的代码添加到我的问题中。 - user2071938
1
尝试使用 tableView:didEndDisplayingCell:forRowAtIndexPath: 来告诉每个单元格在从屏幕中移除时将自己作为观察者移除。 - Wain
@Wain,您认为这对KVO也适用吗? - kernix
1
@Wain 我正在使用带有表视图的VC,其中一些单元格包含集合视图,这些单元格包含与需要观察的模型相关的内容。从视图类中的最后一个点观察模型对我来说是非常合理的,毕竟他们最清楚自己关心什么样的数据。尽管如此,这次我实际上只在VC中进行了观察 - VCs仅刷新可见单元格。我相信iOS单元格毕竟很棘手。 - Jonny
显示剩余6条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接