科学的撸一个秒杀定时器

虽然TableView的重用机制很好用,但是....总有一些很尴尬的业务场景…比如定时器的复用…假如在Cell中定义一个定时器简直重用起来就是爆炸...写之前我也翻阅了一些简书相关的文章,但是...实现起来都太过繁琐和复杂了,有使用通知的(这黑科技)还有用数组把秒数装起来的(坑爹???)….简直不堪入目...所以我决定自己动手丰衣足食,下面开搞吧

思路现实##

_面向对象开发,既然每一个秒杀的数据都是一个对象,只要我让每一个对象都管理自己的定时器不就行了?何必又通知又数组的....同时重用机制每次都是按照indexPath来取自身的Model更加不用纠结定时器重用的问题..好吧,应该这样写,问题都能迎刃而解吧??....先试试再说.. _

  • 首先是通过网络数据转化为Model...

'' //  SeckillListModel.h
'' //
'' //  Created by HuaZao on 16/9/13.
'' //  Copyright © 2016年 HuaZaoGYJ. All rights reserved.
'' //
'' 
'' #import <Foundation/Foundation.h>
'' 
'' typedef NS_OPTIONS(NSUInteger,SeckillState) {
''     //未开始
''     SeckillUnStart       = 0,
''     //进行中
''     SeckillStarting,
''     //已经结束
''     SeckillOver,
'' };
'' 
'' @interface SeckillListModel : NSObject
'' 
'' @property (strong,nonatomic) dispatch_source_t timer;
'' 
'' /** 图片 */
'' @property (nonatomic, copy) NSString* logoImageList;
'' 
'' /** 产品唯一ID */
'' @property (nonatomic, copy) NSString* product_mark_id;
'' 
'' /** 商品ID */
'' @property (nonatomic, assign) NSInteger  Id;
'' 
'' /** 秒杀时间 */
'' @property (nonatomic, copy) NSString* seckill_time;
'' 
'' /** 秒杀保持时间 */
'' @property (nonatomic, assign) NSInteger  keep_time;
'' 
'' /** 已经等待了多长时间 */
'' @property (nonatomic, assign) NSInteger waitTime;
'' 
'' /** 秒杀已经过去的时间 */
'' @property (nonatomic, assign) NSInteger  pass_time;
'' 
'' /** 服务器离开始秒杀或者结束秒杀的时间差 */
'' @property (nonatomic, assign) NSInteger  diffTime;
'' 
'' /** 名字 */
'' @property (nonatomic, copy) NSString* name;
'' 
'' /** 状态 */
'' @property (nonatomic, assign) SeckillState  state;
'' 
'' /** 价钱 */
'' @property (nonatomic, assign) CGFloat  price;
'' 
'' @end
''

Model中的** timer**字段就是负责这个秒杀产品的定时器,这个很重要整个实现的核心!

  • 接下来就是我们撸一个Cell出来

''//
'' //  seckillingCollectionViewCell.m
'' //
'' //  Created by HuaZao on 16/9/12.
'' //  Copyright © 2016年 HuaZaoGYJ. All rights reserved.
'' //
'' 
'' #import "seckillingCollectionViewCell.h"
'' 
'' @interface seckillingCollectionViewCell()
'' 
'' 
'' @end
'' 
'' @implementation seckillingCollectionViewCell
'' 
'' 
'' -(void)loadCellDataWithProductInfoModel:(SeckillListModel *)model{
''     self.goodStr.text = model.name;
''     [self.goodImageView sd_setImageWithURL:[NSURL URLWithString:model.logoImageList] placeholderImage:[UIImage imageNamed:@"ty_tpjzsb_img_nor"]];
''     switch (model.state) {
''         case SeckillUnStart:
''             self.seckillWaitView.hidden = NO;
''             self.seckillOverView.hidden = YES;
''             self.seckillStartView.hidden = YES;
''             self.seckillWaitTime.text = model.seckill_time;
''             [self startSeckillWithModel:model];
''             break;
''         case SeckillStarting:
''             self.seckillWaitView.hidden = YES;
''             self.seckillOverView.hidden = YES;
''             self.seckillStartView.hidden = NO;
''             //开始倒计时
''             [self starTimeCountWithModel:model];
''             break;
''         case SeckillOver:
''             self.seckillWaitView.hidden = YES;
''             self.seckillOverView.hidden = NO;
''             self.seckillStartView.hidden = YES;
''             break;
''         default:
''             break;
''     }
'' }
'' 
'' 
'' /*开始秒杀*/
'' -(void)startSeckillWithModel:(SeckillListModel *)model{
''     //应该去秒杀了
''     if (model.diffTime == 0) {
''         [self starTimeCountWithModel:model];
''         return;
''     }
''     
''     //取真正的时间差
''     __block NSInteger countDiffTime =  model.diffTime - model.pass_time;
''     
''     
''     if (model.timer == nil){
''         dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
''         model.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
''         dispatch_source_set_timer(model.timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
''         //启动定时器
''         dispatch_resume(model.timer);
''     }
''     
''     dispatch_source_set_event_handler(model.timer, ^{
''         countDiffTime --;
''         NSLog(@"商品秒杀倒计时-----%d---%@--",countDiffTime,model.timer);
''         if (countDiffTime == 0) {
''             //关闭这个定时器
''             dispatch_source_cancel(model.timer);
''             model.timer = nil;
''             model.pass_time = 0;
''             model.diffTime = 0;
''             model.state = SeckillStarting;
''             [self starTimeCountWithModel:model];
''             dispatch_async(dispatch_get_main_queue(), ^{
''                 self.seckillWaitView.hidden = YES;
''                 self.seckillOverView.hidden = YES;
''                 self.seckillStartView.hidden = NO;
''             });
''         }
''     });
''     
'' }
'' 
'' 
'' /*已经在秒杀了*/
'' -(void)starTimeCountWithModel:(SeckillListModel *)model{
''     
''     //已经秒完了
''     if (model.pass_time >= model.keep_time || model.diffTime == model.keep_time){
''         self.seckillWaitView.hidden = YES;
''         self.seckillOverView.hidden = NO;
''         self.seckillStartView.hidden = YES;
''         return;
''     }
''     
''     //取真正的时间差
''     NSInteger deffTime = model.keep_time - model.diffTime - model.pass_time;
''     
''     //转分钟
''    __block NSInteger seckillHour = (deffTime/3600);
''    __block NSInteger seckillMinute = (deffTime/60) % 60;
''    __block NSInteger seckillSecond = deffTime % 60;
''     
''     if (model.timer == nil) {
''         dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
''         model.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
''         dispatch_source_set_timer(model.timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
''         //启动定时器
''         dispatch_resume(model.timer);
''     }
''     
''     dispatch_source_set_event_handler(model.timer, ^{
''             seckillSecond --;
''         if (seckillSecond == 0) {
''             if (seckillMinute == 0) {
''                 seckillMinute = 0;
''                 
''             }else{
''                 seckillMinute --;
''                 seckillSecond = 60;
''             }
''         }
''         
''         if (seckillMinute == 0) {
''             if (seckillHour == 0) {
''                 seckillHour = 0;
''             }else{
''                 seckillHour --;
''                 seckillMinute = 60;
''             }
''         }
'' 
''         NSLog(@"-----%d---%@--",model.pass_time,model.timer);
''         if (seckillHour == 0 && seckillMinute ==0 && seckillSecond == 0) {
''             //关闭这个定时器
''             dispatch_source_cancel(model.timer);
''             model.timer = nil;
''             model.pass_time = 0;
''             dispatch_async(dispatch_get_main_queue(), ^{
''                 self.seckillWaitView.hidden = YES;
''                 self.seckillOverView.hidden = NO;
''                 self.seckillStartView.hidden = YES;
''             });
''         }
''         dispatch_async(dispatch_get_main_queue(), ^{
''             self.seckillTime.text = [NSString stringWithFormat:@"%02d:%02d:%02d",(int)seckillHour,(int)seckillMinute,(int)seckillSecond];
''         });
''     });
'' 
'' }
'' '' @end
'' 
'' 
**上面的代码比较多,其实核心代码就几句**
''   if (model.timer == nil){
'' ''         dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
'' ''         model.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
'' ''         dispatch_source_set_timer(model.timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); 
'' ''         dispatch_resume(model.timer);
'' ''     }
'' ''     dispatch_source_set_event_handler(model.timer, ^{
'' //做你要处理的事情
'' });

我们只保证每一个Model的定时器只存在一个Cell重用的时候我们就照样拿出来执行dispatch_source_set_event_handler这个函数就没问题了..这样我们上面的需求已经差不多实现了..不过总觉得差了一点什么.....总有点不对劲....如果这个Model定时器没初始化到岂不是坑爹????这样会造成巨大误差....下面把这个问题解决了吧...那我只需要…在拿到数据的时候计时已经过去的时间不就可以了吗???

  • 解决Cell没有初始化定时器造成的问题

在控制器或者View中定义一个定时器,用来计时已经过去了多少时间

''@implementation seckillingView
'' 
'' /*开始倒计时多余的时间*/
'' -(void)countPassTime{
''     dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
''     _passTime = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
''     dispatch_source_set_timer(_passTime,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
''     dispatch_source_set_event_handler(_passTime, ^{
''         for (SeckillListModel *model in self.viewModel.seckillDataSource) {
''             model.pass_time ++;
''         }
''     });
''     //启动定时器
''     dispatch_resume(_passTime);
'' }
'' @end

在Model中定义一个PassTime用来计算过去的多少时间,具体逻辑可以看前面Cell的实现,我们只需要把服务器时间减去passtime这样就可以解决刚刚的问题了,运行了一下基本实现需求了....收工0.0

  • View源码

''//
'' //  seckillingView.m
'' //
'' //  Created by HuaZao on 16/9/12.
'' //  Copyright © 2016年 HuaZaoGYJ. All rights reserved.
'' //
'' #import "seckillingCollectionViewCell.h"
'' #import "seckillingView.h"
'' #import "TTDKillGoodInfoViewController.h"
'' #import "indexViewController.h"
'' @interface  seckillingView()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
'' 
'' @property (strong,nonatomic) dispatch_source_t passTime;
'' 
'' @end
'' 
'' @implementation seckillingView
'' 
'' /*开始倒计时多余的时间*/
'' -(void)countPassTime{
''     dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
''     _passTime = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
''     dispatch_source_set_timer(_passTime,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
''     dispatch_source_set_event_handler(_passTime, ^{
''         for (SeckillListModel *model in self.viewModel.seckillDataSource) {
''             model.pass_time ++;
''         }
''     });
''     //启动定时器
''     dispatch_resume(_passTime);
'' }
'' 
'' -(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
''     return self.viewModel.seckillDataSource.count;
'' }
'' 
'' -(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
''     seckillingCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"seckillCell" forIndexPath:indexPath];
''     [cell loadCellDataWithProductInfoModel:self.viewModel.seckillDataSource[indexPath.row]];
''     return cell;
'' }
'' 
'' 
'' -(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
''     TTDKillGoodInfoViewController *killVc = [[TTDKillGoodInfoViewController alloc] init];
''     killVc.seckModel = self.viewModel.seckillDataSource[indexPath.row];
''     killVc.goodId = self.viewModel.seckillDataSource[indexPath.row].product_mark_id;
''     [self.viewModel.indexVc.navigationController pushViewController:killVc animated:YES];
'' }
'' 
'' 
'' @end
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,425评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,058评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,186评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,848评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,249评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,554评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,830评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,536评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,239评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,505评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,004评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,346评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,999评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,060评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,821评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,574评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,480评论 2 267

推荐阅读更多精彩内容