比如我们在写消息列表的时候,未读消息一般都有个红点,点击一下红点消失。这个功能通常的做法就是Model中标识消息已读。然后在Reload TableView或者Cell。 但是还有个方法可以实现那个就是KVO
#import "MessageCell.h"
@implementation MessageCell
- (void)awakeFromNib {
[super awakeFromNib];
// Initialization code
self.bradgeView.layer.masksToBounds = YES;
self.bradgeView.layer.cornerRadius = 5;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (void)setMsgModel:(MessageModel *)msgModel{
_msgModel = msgModel;
self.msgLbl.text = msgModel.msgTitle;
if ([msgModel.isRead integerValue] == 1) {
self.bradgeView.hidden = YES;
}else{
self.bradgeView.hidden = NO;
}
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
if ([keyPath isEqualToString:@"isRead"] && [object isKindOfClass:[MessageModel class]]) {
if ([self.msgModel.isRead integerValue] == 1) {
_bradgeView.hidden = YES;
}
}
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(nonnull UITableViewCell *)cell forRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
if (_msgDataArr.count > indexPath.row) {
MessageModel *msgModel = _msgDataArr[indexPath.row];
[msgModel addObserver:cell forKeyPath:@"isRead" options:NSKeyValueObservingOptionNew context:nil];
}
}
- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(nonnull UITableViewCell *)cell forRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
if (_msgDataArr.count > indexPath.row) {
MessageModel *msgModel = _msgDataArr[indexPath.row];
[msgModel removeObserver:cell forKeyPath:@"isRead"];
}
}
使用KVO来监听isRead属性,当点击Cell的时候处理
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
MessageModel *msgModel = _msgDataArr[indexPath.row];
if ([msgModel.isRead integerValue] != 1) {
msgModel.isRead = @"1";
}
}