`這次的項(xiàng)目里面有涉及到商品的倒計時功能岂座,UIcollectionview中羅列商品進(jìn)行倒計時,以前頂多就是密碼找回,獲取驗(yàn)證碼配紫,或者輪播圖簡單的使用了一下NSTimer。之前還因?yàn)閠imer使用不恰當(dāng)造成了內(nèi)存持續(xù)飆高午阵,直接crash的情況躺孝。。。銷毀timer需要使用invalidate植袍,直接設(shè)置nil并不能銷毀惧眠。
這次使用GCD定時器進(jìn)行功能簡單實(shí)現(xiàn),其中也是找了一些資料于个,看了其他大神的代碼氛魁,然后自己寫了一個demo,僅作為筆記方便以后自己查看览濒,完善呆盖。
demo地址:https://github.com/w467364316/GoodTimerDemo.git
放代碼:
工具類.h
@interface CutDown : NSObject
-(void)creatTimerWit:(void(^)())completeBlock;
-(void)destroyTimer;
@end
創(chuàng)建定時器,設(shè)定間隔時間為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內(nèi)部贷笛,在viewDidLoad方法中調(diào)用cutDown 創(chuàng)建定時器
- (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];
}
//開始進(jìn)行計時
self.cutDown = [[CutDown alloc] init];
__weak typeof(self) weakSelf = self;
[self.cutDown creatTimerWit:^{
[weakSelf updateVisialCells];
}];
}
GoodTimeModel參數(shù)
@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
更新當(dāng)前視圖內(nèi)的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;
}
}
設(shè)置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中進(jìn)行計算顯示剩余時間
-(void)setModel:(GoodTimeModel *)model{
_model = model;
self.numerLabel.text = model.number;
self.minSecondLabel.text = model.minSecond;
[self setTimeWithLastTime:model.time beginTime:model.beginTime];
}
/**
* 開始進(jìn)行倒計時
*
* @param time 結(jié)束時間
*/
-(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) {
//活動結(jié)束
self.timerLabel.text = @"活動結(jié)束";
}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];
}