基本上,我有一个可以包含多个NSManagedObjects的数组,我正在尝试对这些对象进行排序,对于那些有开始日期的对象,我想要比较开始日期和现在之间的时间,或者开始日期和结束日期之间的时间(如果设置了)。最后,设置一个计时器,以便在一秒钟内刷新此信息。
我遇到的问题是,当比较时间时,只返回第一个对象的值和开始日期。如果我将另一个值与开始日期相加,则时间设置为0,并在我希望将它们相加时重新开始。
如果您需要更多信息,请让我知道
我以前使用过for(数组中的对象*obj ),但是它似乎有更多的问题
int time = 0;
if([_ttimes count] != 0){
for(int i=0; i < [_ttimes count]; ++i){
TTime *tTime = [_ttimes objectAtIndex:i];
NSLog(@"time%i", i);
if(tTime.sDate){
NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *date = [NSDate date];
if(tTime.eDate){
date = tTime.eDate;
}
NSDateComponents *component = [cal components:NSSecondCalendarUnit fromDate:tTime.sDate toDate:date options:0];
int tmpTime = [component second];
time = time + tmpTime;
}
}
_ticketTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(TotalWorkTime) userInfo:nil repeats:NO];
}将方法更改为:
-(void)TotalWorkTime{ double time = 0; if([_ttimes count] != 0){ for(TTime *tTime in _ttimes){ NSDate *date = [NSDate date]; if(tTime.eDate){ date = tTime.eDate; } NSTimeInterval timerint = -[tTime.sDate timeIntervalSinceDate:date]; time = time + timerint; } NSLog(@"Time:%f", time); } }
这似乎返回了一个更准确的时间,但是,谢谢你,Zaph,但这仍然没有解决问题,时间+=定时器不工作,这个数字重置每次我添加一个新的对象,它也只返回最后添加的对象的值。
发布于 2014-06-01 02:47:20
NSDateComponents components:NSSecondCalendarUnit的问题是它只返回0-59。(有罕见的例外)
此外,由于您每秒都会触发一个计时器,因此秒(0-59)很有可能是相同的。要检查这一点,在if(tTime.sDate)之后添加日志记录
NSLog(@"tTime.sDate: %@", tTime.sDate);看看日期是否真的一样,只是秒是一样的。
而不是这样:
NSDateComponents *component = [cal components:NSSecondCalendarUnit fromDate:tTime.sDate toDate:date options:0];
int tmpTime = [component second];
time = time + tmpTime;试试这个:
NSTimeInterval tmpTime = -[tTime.sDate timeIntervalSinceDate:date];
time += tmpTime;https://stackoverflow.com/questions/23973402
复制相似问题