iOS - 收到NSNotification后调用UITableViewCell的awakeFromNib

时间:2017-12-05 03:34:56

标签: ios objective-c uitableview

awakeFromNib中调用UITableViewCell时添加了NSNotification观察者。然后,我在调用removeFromSuperView时删除了观察者。

- (void)awakeFromNib
{
    [super awakeFromNib];

    [self setNotificationObserver];

    _vHolder.layer.cornerRadius = 10.0f;
    _vHolder.layer.shadowColor = [UIColor blackColor].CGColor;
    _vHolder.layer.shadowRadius = 2.0f;
    _vHolder.layer.shadowOffset = CGSizeMake(0.0f, 0.0f);
    _vHolder.layer.shadowOpacity = 0.5f;
}

- (void)removeFromSuperview
{
    [super removeFromSuperview];

    [self removeNotificationObserver];
}

- (void)setNotificationObserver
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveESSMQTTMessageNotification:) name:NOTIF_ESSMQTT_MESSAGE_RECEIVED object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveDeviceStatesMessageNotification:) name:NOTIF_DEVICE_STATES_RECEIVED object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveDeviceOnOffStateNotification:) name:NOTIF_DEVICE_ON_OFF_STATE_RECEIVED object:nil];
}

- (void)removeNotificationObserver
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NOTIF_ESSMQTT_MESSAGE_RECEIVED object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NOTIF_DEVICE_STATES_RECEIVED object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NOTIF_DEVICE_ON_OFF_STATE_RECEIVED object:nil];
}

我正在使用NSNotification刷新此UITableViewCell中我的按钮和图片的状态。

我面临的问题是,每次收到NSNotication时,都会调用awakeFromNib。这将导致我的按钮和图像的状态刷新回其初始状态。 奇怪的是,我之前从未见过removeFromSuperview被调用。

所以我的问题是:

  1. 为什么在收到awakeFromNib时会调用NSNotification

  2. 我只是想知道,当您希望awakeFromNib观察UITableViewCells时,在NSNotifications下添加观察者是正确的做法吗? (好吧,我一直这样做。)

1 个答案:

答案 0 :(得分:0)

因为您的单元格已刷新内容但未从superview中删除

当成功刷新单元格内容时,必须调用removeNotificationObserver。

我建议您使用协议而不是通知。

希望帮助。