美文网首页Objective-C好东西小知识点
TableViw加载倒计时,一个定时器完美解决。

TableViw加载倒计时,一个定时器完美解决。

作者: MaShuai丨 | 来源:发表于2017-05-02 15:30 被阅读81次
群里有小伙伴问倒计时的问题,写了一个小Demo。今天整理笔记的时候顺便发上来。

听到这个上面的这个需求,第一点你会想到什么了,定时器没错,接下来是cell 里面放定时器吗,那么如果是这样的话会产生什么样的后果呢?负责这个项目的同事就是这样做的,tableview 显示出来没多久,由于创建的定时器过多程序就卡死了,cell 的高度100左右 ,在iphone 6的屏幕大致创建 至少6个定时器左右(只是在屏幕内的cell 创建定时器)这个足以导致性能下降。

思路:
1、将数据(数据中的时间部分),以字典(字典中包括:记录所存数据下标,还有所剩时间 两个 key)的形式保存到数组中。
2、开启定时器,执行:遍历整个数组,每秒减 一,然后保存到他原来的位置。
3、每次减一之后,根据之前记录的下标找到对应的Cell,然后修改上面的数。这样就可以了
下面上代码

static  NSString  * const indexPathKey =@"indexPath";
static  NSString  * const showTimeKey =@"showTime";

@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *myTableView;
@property (nonatomic, strong) NSTimer *timer; /// 定时器
@property (nonatomic, strong) NSMutableArray *times; /// 时间数组
@property (nonatomic, strong) NSMutableArray *showTimes; /// 显示倒计时数组
@end
- (void)viewDidLoad {
    [super viewDidLoad];
    _times = [NSMutableArray array];
    
    _showTimes = [NSMutableArray array];
    
    
    //模拟倒计时数据
    
    for (int i=0; i<30; i++) {
        
        NSInteger time = (arc4random() % 30) + 100;
        
        [_times addObject:[NSString stringWithFormat:@"%ld",time]];
        
        NSDictionary *timedic = @{indexPathKey:[NSString stringWithFormat:@"%i",i],
                                  showTimeKey: [NSString stringWithFormat:@"%ld",time]};
        
        [_showTimes addObject:timedic];
    }
    
    _myTableView=[[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    
    _myTableView.delegate=self;
    
    _myTableView.dataSource=self;
    
    _myTableView.rowHeight=80.0f;
    
    [self.view addSubview:_myTableView];
    
    
    // 创建定时器
    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(countdown) userInfo:nil repeats:YES];
        
        [[NSRunLoop currentRunLoop] addTimer:_timer forMode:UITrackingRunLoopMode];
        
    }
}

#pragma mark - TableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return _showTimes.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *cellID =@"cellid";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    
    cell.textLabel.text= [NSString stringWithFormat:@"活动结束还剩下:%@ 秒", _times[indexPath.row]];
    
    return cell;
    
}

// 处理逻辑

- (void)countdown{
    
    NSInteger time;
    
    for (int i = 0; i < _showTimes.count; i++) {
        
        time = [_showTimes[i][showTimeKey] integerValue];
        
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[_showTimes [i][indexPathKey] integerValue] inSection:0];
        
        UITableViewCell *cell = [_myTableView cellForRowAtIndexPath:indexPath];
        
        if (time > 0) {
            cell.textLabel.text =[NSString stringWithFormat:@"活动结束还剩下:%ld 秒", time];
            time --;
            NSDictionary *dic = @{indexPathKey: [NSString stringWithFormat:@"%d",i],
                                  showTimeKey: [NSString stringWithFormat:@"%ld",time]};
            
            [_showTimes replaceObjectAtIndex:i withObject:dic];
            
        }else {
            
            cell.textLabel.text = [NSString stringWithFormat:@"活动已结束"];
            
        }
        
    }
    
}
//销毁定时器
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
        
    }
}

运行后的结果

Demo.gif

相关文章

网友评论

    本文标题:TableViw加载倒计时,一个定时器完美解决。

    本文链接:https://www.haomeiwen.com/subject/ccgctxtx.html