1. 程式人生 > >關於倒計時的小demo學習

關於倒計時的小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];
}

相關推薦

關於倒計時demo學習

`這次的專案裡面有涉及到商品的倒計時功能,UIcollectionview中羅列商品進行倒計時,以前頂多就是密碼找回,獲取驗證碼,或者輪播圖簡單的使用了一下NSTimer。之前還因為timer使用不恰當造成了記憶體持續飆高,直接crash的情況。。。銷燬time

倒計時demo

window.addEventListener('load', function() { countTime(); }) function countTime() { var date = new Date(); var now = d

TP5學習基礎一:增刪改查demo

表單 arr 處理 php req 學習 model類 浪費 新手 ①TP5--增刪改查簡單的demo 我先吐槽一下:因為工作需要研究tp5,去官網看了一下哎呦,資源挺多挺全啊!然後下載唯一免費的官方教程,我曹pdf打開533頁。講的很細但是開發能等看完才做嗎?看到精簡版快

Hadoop學習:Map/Reduce初探與Demo實現

pre 排序。 解決 想法 文本文 direction run page lang 一、 概念知識介紹 Hadoop MapReduce是一個用於處理海量數據的分布式計算框架。這個框架攻克了諸如數據分布式存儲、作業調度、容錯、機器間通信等復雜

java之Spring學習之前的一個demo

服務 err const 對象 color void del () 添加 寫這個小demo呢,是為了在學習Spring之前,練習一下傳統的model2開發模式; 為了簡化流程,這裏省略了利用servlet來獲取前臺數據。 采用直接new出來的對象來交給程序處理,然後執行

【Vue.js學習筆記】7:v-for渲染,Vue的Demo

v-for渲染 v-for是Vue中常用的列表渲染方法, 可以將一個列表渲染為一系列的HTML元素,也可以用來遍歷物件內的k-v對。另外關於模板元素渲染在官方文件上見這裡。 index.html <!DOCTYPE html> <html lang="en"

react基礎學習demo彙總

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>react demo</title> <scr

shell學習Demo

檔案操作命令wc #!/bin/bash echo 顯示行數 wc -l demo01.sh echo 顯示檔案中最長行的長度 wc -L demo01.sh echo 顯示Bytes數 wc -c demo01.sh 顯示行數 7 demo01.sh 顯示檔案中最長行的長

python學習Demo

練習一 :拆數字遊戲 #coding=utf-8 import random game_count=0 all_counts=[] while True: game_count+=1 guess_count =0 answer=random.randint(0,

Unity3d 區域網遊戲DEMO學習

今天看了SIKI老師的區域網多人聯機小遊戲,記錄下: 首先新建GameObject,新增NetworkManager元件和NetworkManagerHUD元件。 1.NetworkManager:Spawn Info->PlayerPrefab可放置prefab,在

JUC學習之執行緒通訊Demo

按照順序列印執行緒A、B、C,共列印五輪: public class Test { public static void main(String[] args) { AlternatePrinting printing = new A

vuejs學習系列-第一個demo

現在上節中安裝的專案的src目錄中建立pages檔案用來裝demo原始碼 我們現在的目錄結構是這樣的 首先在pages裡新建demo01資料夾,順便在demo01下,建立index.vue檔案,然後在router裡新增 { path: '/

netty學習三:基於socket的聊天demo

服務端程式碼 package chat.server; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty

netty學習一:用netty構造http服務的demo

概述 netty可以支援http、socket、websocket,本文會做一個小demo,簡單介紹一下如何用netty搭建一個http服務。 netty雖然可以提供http服務,但是相比spring mvc、struts2等框架,netty顯得比較底層

初次使用Fleck+redis訂閱發布實現學習demo

直接 一次 align -s 按鈕 for 添加引用 加油 訂閱發布 首先安裝Fleck的程序包添加引用下面是客戶端代碼: 客戶端代碼: 運行效果: 遇到的問題: Q:通常每個套接字地址(協議/網絡地址/端口)只允許使用一次 A:是因為本萌新

netty學習二:基於socket通訊的demo

概述 上次寫了一篇netty學習一:用netty構造http服務的小demo 簡單介紹如何使用netty編寫http程式,而基於socket程式設計才是netty的強項。 服務端程式碼 package socket.server; im

QT學習demo之LightMD(MarkDown編輯器)

很早之前就有了寫一個類似Windows記事本的想法,加上最近也剛好在學編譯原理,所以就想把兩者結合起來,於是就打算結合MarkDown,開發一款MarkDown編輯器。 不過由於我之前一直使用的是Java語言居多,對c++並不熟悉,所以一些糟糕的程式碼風格和規範還望各位大佬諒解! LightMD 即一款基

css3的一個demo(箭頭hover變化)

rotate osi ping align pos ref block translate -m 1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta char

微信程序學習筆記1

接口 spa class 搭建 name demo title 更新數據 navigate 初步接觸微信小程序開發 微信小程序的開發環境     微信小程序是運行在微信環境中的應用,它只能在微信中運行,不能運行在瀏覽器等其他環境中,微信團隊提供了專門開發工具用於小程

白滴滴系列》-線程和進程(學習,內容均參考網絡資料)

多個 系統 資料 搶占式 線程 並發 強制 資源 資源分配 1、進程就是操作系統將資源分配成一塊一塊的內存 2、線程就是在進程中運行的多個程序 3、線程是程序運行的最小單位,而進程則是分配資源的最小單位。 4、一個進程可以有多個線程 5、任務調度:采取時間片輪轉搶占式執行,