關于倒計時的小demo學習

`這次的項目里面有涉及到商品的倒計時功能,UIcollectionview中羅列商品進行倒計時,以前頂多就是密碼找回,獲取驗證碼,或者輪播圖簡單的使用了一下NSTimer。之前還因為timer使用不恰當造成了內存持續飆高,直接crash的情況。。。銷毀timer需要使用invalidate,直接設置nil并不能銷毀。

這次使用GCD定時器進行功能簡單實現,其中也是找了一些資料,看了其他大神的代碼,然后自己寫了一個demo,僅作為筆記方便以后自己查看,完善。
demo地址:https://github.com/w467364316/GoodTimerDemo.git

demo圖.png

放代碼:
工具類.h

@interface CutDown : NSObject

-(void)creatTimerWit:(void(^)())completeBlock;

-(void)destroyTimer;
@end

創建定時器,設定間隔時間為0.1秒


@interface CutDown ()

@property(nonatomic,strong) dispatch_source_t timer;

@end

@implementation CutDown
-(void)creatTimerWit:(void(^)())completeBlock{

    if (_timer == nil) {
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
        dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 0.1*NSEC_PER_SEC, 0);
        dispatch_source_set_event_handler(_timer, ^{
           dispatch_async(dispatch_get_main_queue(), ^{
               completeBlock();
           });
        });
        dispatch_resume(_timer);
    }
}

-(void)destroyTimer{
    if (_timer) {
        dispatch_source_cancel(_timer);
        _timer = nil;
    }
    
}
@end

viewController內部,在viewDidLoad方法中調用cutDown 創建定時器

- (void)viewDidLoad {
    
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.myCollection.backgroundColor = [UIColor whiteColor];
    self.dataArray = [NSMutableArray array];
    [self.myCollection registerNib:[UINib nibWithNibName:@"TimerCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"timeCell"];
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"GoodsTimes" ofType:@".plist"];
    NSArray *array = [NSArray arrayWithContentsOfFile:path];
    
    for (NSDictionary *dic in array) {
        GoodTimeModel *model = [GoodTimeModel initWithDic:dic];
        [self.dataArray addObject:model];
    }
    //開始進行計時
    self.cutDown = [[CutDown alloc] init];
    __weak typeof(self) weakSelf = self;
    [self.cutDown creatTimerWit:^{
        [weakSelf updateVisialCells];
    }];
}
plist.png

GoodTimeModel參數

@interface GoodTimeModel : NSObject
@property(nonatomic,copy) NSString *number;//序號
@property(nonatomic,copy) NSString *beginTime;//開始時間
@property(nonatomic,copy) NSString *time;//時間
@property(nonatomic,copy) NSString *minSecond;//毫秒

+(instancetype)initWithDic:(NSDictionary*)dic;
-(instancetype)initWithDic:(NSDictionary*)dic;

@end

更新當前視圖內的cell的顯示信息

/**
 *  更新cell
 */
-(void)updateVisialCells{
    
    NSArray *cells = self.myCollection.visibleCells;
    for (TimerCollectionViewCell *cell in cells) {
        GoodTimeModel *model = self.dataArray[cell.tag];
        int minSec = [model.minSecond intValue];
        if (minSec <=0) {
            minSec = 9;
        }else{
            minSec --;
        }
        model.minSecond = [NSString stringWithFormat:@"%d",minSec];
        cell.model = model;
    }
}

設置cell部分

-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    TimerCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"timeCell" forIndexPath:indexPath];
    GoodTimeModel *model = self.dataArray[indexPath.row];
    cell.model = model;
    cell.tag = indexPath.row;
    return cell;
}

TimerCollectionViewCell中進行計算顯示剩余時間

-(void)setModel:(GoodTimeModel *)model{
    
    _model = model;
    self.numerLabel.text = model.number;
    self.minSecondLabel.text = model.minSecond;
    [self setTimeWithLastTime:model.time beginTime:model.beginTime];
}

/**
 *  開始進行倒計時
 *
 *  @param time 結束時間
 */
-(void)setTimeWithLastTime:(NSString*)time beginTime:(NSString*)beginTime{

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSDate *endDate = [formatter dateFromString:time];
    NSDate *nowDate = [NSDate date];
    
    NSDate *beginDate = [formatter dateFromString:beginTime];
    NSTimeInterval beginTimeInterval = [beginDate timeIntervalSinceDate:nowDate];
    
    //剩余時間
    NSTimeInterval timeInterval = [endDate timeIntervalSinceDate:nowDate];
    self.minSecondLabel.hidden = YES;
    if (timeInterval <=0) {
        //活動結束
        self.timerLabel.text = @"活動結束";
    }else if (beginTimeInterval > 0){
         //活動未開始
          self.timerLabel.text = @"活動未開始";
    }else{
        self.minSecondLabel.hidden = NO;
        int day = (int)timeInterval/(3600*24);
        int hours = (int)(timeInterval - day*3600*24)/3600;
        int minus = (timeInterval - day*24*3600 - hours*3600)/60;
        int second = (timeInterval - day*3600*24 - hours*3600- minus*60);
        
        //小時
        NSString *finalHours = [NSString stringWithFormat:@"%d",day*24 + hours];
        if ([finalHours intValue] <10) {
            finalHours = [NSString stringWithFormat:@"0%@",finalHours];
        }
        //分鐘
        NSString *finalMinutes = [NSString stringWithFormat:@"%d",minus];
        if ([finalMinutes intValue] <10) {
            finalMinutes = [NSString stringWithFormat:@"0%@",finalMinutes];
        }
        //秒
        NSString *finalSeconds = [NSString stringWithFormat:@"%d",second];
        if ([finalSeconds intValue] < 10) {
            finalSeconds = [NSString stringWithFormat:@"0%@",finalSeconds];
        }
        self.timerLabel.text = [NSString stringWithFormat:@"%@:%@:%@",finalHours,finalMinutes,finalSeconds];
    }
}
-(void)dealloc{
    
    NSLog(@"class = %s",object_getClassName(self));
    [_cutDown destroyTimer];
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,436評論 25 708
  • 李杜光芒在 詩意天水情 首屆“中國天水·李杜詩歌獎”在天水頒獎 主持人在主持首屆“中國天水·李杜詩歌獎”頒獎晚會...
    讀寫人家閱讀 545評論 0 1
  • 過去,中國卻大多數人都是使用批評教育法,然后據研究,這種做法給人帶來的影響就是培訓了一代又一代不夠自信的人。于是乎...
    CL生涯規劃師閱讀 581評論 0 0
  • 引言 以前車馬很遠,書信很慢,一生只夠認真愛一個人。可現在的我們,處于一個匆匆忙忙的信息時代,卻再也提不起勇氣去愛...
    陳大白閱讀 1,326評論 5 8