@implementation GoodsViewController
{
dispatch_source_t _timer;
}
// 求两个时间的时, 分 ,秒
+(NSArray *)getTwoDataMin:(NSString *)stamp1 andWith:(NSString *)stamp2{
NSTimeInterval timeInterval1 = [stamp1 doubleValue];
NSTimeInterval timeInterval2 = [stamp2 doubleValue];
NSDate *dateBefore1 = [NSDate dateWithTimeIntervalSince1970:timeInterval1];
NSDate *dateBefore2 = [NSDate dateWithTimeIntervalSince1970:timeInterval2];
// NSDateFormatter *dateFormat=[[NSDateFormatter alloc] init];
// [dateFormat setDateFormat:@"HH:mm:ss"];
// NSString * date1 =[dateFormat stringFromDate:dateBefore1];
// NSString * date2 =[dateFormat stringFromDate:dateBefore1];
// 当前日历
NSCalendar *calendar = [NSCalendar currentCalendar];
// 需要对比的时间数据
NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth
| NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
// 对比时间差
NSDateComponents *dateCom = [calendar components:unit fromDate:dateBefore1 toDate:dateBefore2 options:0];
NSArray * dataArray = @[[NSString stringWithFormat:@"%ld",dateCom.hour],[NSString stringWithFormat:@"%ld",dateCom.minute],[NSString stringWithFormat:@"%ld",dateCom.second]];
return dataArray;
}
//_timeArray 上个方法返回的数组
-(void)timeToActivity{
if (_timer==nil) {
__block int second = [_timeArray[2] intValue];
__block int min = [_timeArray[1] intValue];
__block int hour = [_timeArray[0] intValue];
if (second==0&&min==0&&hour==0) {
}else{
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),1.0*NSEC_PER_SEC, 0); //每秒执行
dispatch_source_set_event_handler(_timer, ^{
if(second==0&&min==0&&hour==0){ //倒计时结束,关闭
dispatch_source_cancel(_timer);
_timer = nil;
dispatch_async(dispatch_get_main_queue(), ^{
endHour.text = @"00";
endMin.text = @"00";
endSecond.text = @"00";
});
}else{
dispatch_async(dispatch_get_main_queue(), ^{
endHour.text = [NSString stringWithFormat:@"%d",hour];
endMin.text = [NSString stringWithFormat:@"%d",min];
endSecond.text = [NSString stringWithFormat:@"%d",second];
if (second==0&&min>0&&hour>=0) { // 01:20:00
second = 60;
min--;
}else if (second==0&&min==0&&hour>0) { //01:00:00
second=60;
min=59;
hour--;
}
});
second--;
}
});
dispatch_resume(_timer);
}
}
}