首页 > 代码库 > 利用kvo实现列表倒计时

利用kvo实现列表倒计时

自己稍微记录一下,方便以后用到:

先创建一个定时器的类:

#import "TimeCenter.h"
@interface TimeCenter ()
@property (nonatomic, assign) NSInteger timeInterval;// 累计时间
@property (nonatomic, strong) NSTimer *timer;

@end
@implementation TimeCenter
+ (instancetype)shareCenter {
    static TimeCenter *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[TimeCenter alloc]init];
    });
   
    return center;
}
//启动
- (void)start {
   NSTimer  *timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerEvent) userInfo:nil repeats:YES];
    self.timer=timer;
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}
//停止
- (void)stop
{
     if (_timer != nil) {
         [self.timer invalidate];
     }
}

//事件
- (void)timerEvent
{
    if (_timer != nil) {
        self.timeInterval++;
    }
}

在控制器创建的时候开始定时器,

然后在cell中添加kvo 监听事件:

@implementation TableViewCell
+ (instancetype)cellWithTableView:(UITableView *)tableView{
    static NSString *ID = @"tableViewCell";
    TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        cell = [[TableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
    }
    return cell;
}

- (id)initWithStyle:(UITableViewCellStyle)style
    reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        //第二种:KVO监听
        [[TimeCenter shareCenter] addObserver:self
                                   forKeyPath:@"timeInterval"
                                      options:NSKeyValueObservingOptionOld
         |NSKeyValueObservingOptionNew
                                      context:nil];
    }
    return self;
}

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context{
    if ([keyPath isEqual:@"timeInterval"]) {
        [self reloadCell];
    }
}

- (void)setTimeModel:(TimeModel *)timeModel{
    _timeModel=timeModel;
    [self reloadCell];
}

- (void)reloadCell{
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:0];
    NSInteger time = [date timeIntervalSince1970];
    NSInteger leftTime = [self.timeModel.time integerValue] - time;
    if (leftTime <0){
        self.textLabel.text =@"已结束";
    }else{
        self.textLabel.text = [NSString stringWithFormat:@"剩余%ld天%02ld:%02ld:%02ld",  leftTime/(60*60*24),
                               (leftTime/3600)%24,
                               (leftTime/60)%60,
                               leftTime%60];
    }
}
- (void)dealloc
{
    [[TimeCenter shareCenter] removeObserver:self
                                  forKeyPath:@"timeInterval"];

 

利用kvo实现列表倒计时