@implementation GoodsViewController
{
dispatch_source_t _timer;
}
// 求两个时间的时, 分 ,秒
+(NSArray *)getTwoDataMin:(NSString *)stamp1 andWith:(NSString *)stamp2{
NSTimeInterval timeInterval1 = [stamp1doubleValue];
NSTimeInterval timeInterval2 = [stamp2doubleValue];
NSDate *dateBefore1 = [NSDatedateWithTimeIntervalSince1970:timeInterval1];
NSDate *dateBefore2 = [NSDatedateWithTimeIntervalSince1970:timeInterval2];
// NSDateFormatter *dateFormat=[[NSDateFormatter alloc] init];
// [dateFormat setDateFormat:@"HH:mm:ss"];
// NSString * date1 =[dateFormat stringFromDate:dateBefore1];
// NSString * date2 =[dateFormat stringFromDate:dateBefore1];
// 当前日历
NSCalendar *calendar = [NSCalendarcurrentCalendar];
// 需要对比的时间数据
NSCalendarUnit unit =NSCalendarUnitYear | NSCalendarUnitMonth
| NSCalendarUnitDay |NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
// 对比时间差
NSDateComponents *dateCom = [calendarcomponents:unit fromDate:dateBefore1toDate:dateBefore2 options:0];
NSArray * dataArray =@[[NSStringstringWithFormat:@"%ld",dateCom.hour],[NSStringstringWithFormat:@"%ld",dateCom.minute],[NSStringstringWithFormat:@"%ld",dateCom.second]];
return dataArray;
}
//_timeArray 上个方法返回的数组
-(void)timeToActivity{
if (_timer==nil) {
__blockint second = [_timeArray[2]intValue];
__blockint min = [_timeArray[1]intValue];
__blockint 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 = [NSStringstringWithFormat:@"%d",hour];
endMin.text = [NSStringstringWithFormat:@"%d",min];
endSecond.text = [NSStringstringWithFormat:@"%d",second];
if (second==0&&min>0&&hour>=0) { // 01:20:00
second = 60;
min--;
}elseif (second==0&&min==0&&hour>0) { //01:00:00
second=60;
min=59;
hour--;
}
});
second--;
}
});
dispatch_resume(_timer);
}
}
}