我有以下代碼。這是在cellForRowAtIndexPath計算,所以我認爲它可能有點貴。有沒有更好的方法來計算一個時間段?有沒有更好的方法來計算一個時間段?
+(NSString*)toShortTimeIntervalString:(NSString*)sDate
{
NSDateFormatter* df = [[NSDateFormatter alloc]init];
[df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
NSDate* date = [df dateFromString:[sDate stringByReplacingOccurrencesOfString:@"Z" withString:@"-0000"]];
[df release];
NSDate* today = [[NSDate alloc] init];
NSDate *d = date; //[_twitter_dateFormatter dateFromString:sDate];
NSTimeInterval interval = [today timeIntervalSinceDate:d];
[today release];
//TODO: added ABS wrapper
double res = 0;
NSString* result;
if(interval > SECONDS_IN_WEEK)
{
res = fabs(interval/SECONDS_IN_WEEK);
result = [NSString stringWithFormat:@"%1.0fw ago", res];
}
else if(interval > SECONDS_IN_DAY)
{
res = fabs(interval/SECONDS_IN_DAY);
result = [NSString stringWithFormat:@"%1.0fd ago", res];
}
else if (interval > SECONDS_IN_HOUR){
res = fabs(interval/SECONDS_IN_HOUR);
result = [NSString stringWithFormat:@"%1.0fh ago", res];
}
else if (interval > SECONDS_IN_MIN) {
res = fabs(interval/SECONDS_IN_MIN);
result = [NSString stringWithFormat:@"%1.0fm ago", res];
}
else
{
interval = fabs(interval);
result = [NSString stringWithFormat:@"%1.0fs ago", interval];
}
return result;
}
這對我來說看起來很好,我懷疑它太慢了。 –
不要假設,測量。如果你測量它並且速度太慢,那麼找出這樣做的方法,然後詢問如何改進。如果你不知道如何測量或如何描述,那就詢問一下。 「你認爲這太慢了嗎?」並不是一個好問題。 –
Josh,我測量了它,佔用了62%的時間花費了 –