//所有剩余時間數(shù)組
NSMutableArray *totalLastTime;
在網(wǎng)絡(luò)請求到的所有數(shù)據(jù)中被饿,根據(jù)需要將其中要進(jìn)行倒計時顯示的數(shù)據(jù)中的剩余時間單獨(dú)保存出來,如果這里是所有的數(shù)據(jù)都需要倒計時,則只需要保存時間即可化焕,如果是有部分?jǐn)?shù)據(jù)才需要倒計時,則可以保存字典,兩個鍵值對分別為其在UITableView的indexPath和剩余時間:num默認(rèn)從0開始
NSDictionary *dic = @{@"indexPath":[NSStrin stringWithFormat:@"%i",num],@"lastTime": order.payLastTime};
[totalLastTime addObject:dic];
開啟定時器方法:
- (void)startTimer{
timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(refreshLessTime) userInfo:@"" repeats:YES];
如果不添加下面這條語句矢门,在UITableView拖動的時候,會阻塞定時器的調(diào)用
[[NSRunLoop currentRunLoop] addTimer:timer forMode:UITrackingRunLoopMode];
}
主要的定時器中的方法灰蛙,在該方法中祟剔,遍歷totalLastTime,取出其中保存的lasttime和indexpath缕允,time用來顯示峡扩,在顯示完后自減,indexpath代表對應(yīng)顯示的位置障本,在一次循環(huán)后教届,將新的time和沒有改變的indexpath從新替換totalLastTime 中對應(yīng)位置的元素,以此保證每一秒執(zhí)行時驾霜,顯示time都是最新的案训。
- (void)refreshLessTime
{
NSUInteger time;
for (int i = 0; i < totalLastTime.count; i++) {
time = [[[totalLastTime objectAtIndex:i] objectForKey:@"lastTime"] integerValue];
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:[[[totalLastTime objectAtIndex:i] objectForKey:@"indexPath"] integerValue]];
WLServiceOrderTableViewCell *cell = (WLServiceOrderTableViewCell *)[_tableView cellForRowAtIndexPath:indexPath];
cell.remainingTimeLabel.text = [NSString stringWithFormat:@"剩余支付時間:%@",[self lessSecondToDay:--time]];
NSDictionary *dic = @{@"indexPath": [NSString stringWithFormat:@"%i",indexPath.section],@"lastTime": [NSString stringWithFormat:@"%i",time]};
[totalLastTime replaceObjectAtIndex:i withObject:dic];
}
}
- (NSString *)lessSecondToDay:(NSUInteger)seconds
{
NSUInteger day? = (NSUInteger)seconds/(24*3600);
NSUInteger hour = (NSUInteger)(seconds%(24*3600))/3600;
NSUInteger min? = (NSUInteger)(seconds%(3600))/60;
NSUInteger second = (NSUInteger)(seconds%60);
NSString *time = [NSString stringWithFormat:@"%lu日%lu小時%lu分鐘%lu秒",(unsigned long)day,(unsigned long)hour,(unsigned long)min,(unsigned long)second];
return time;
}