【发布时间】:2011-06-26 21:59:25
【问题描述】:
我有以下代码。这是在 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;
}
【问题讨论】:
-
这对我来说看起来不错,但我怀疑它太慢了。
-
不要假设,要衡量。如果你测量它并且它太慢了,找出是什么造成了这种情况,然后询问如何改进它。如果您不知道如何衡量或如何分析,请询问。 “你觉得这太慢了吗?”这不是一个很好的问题。
-
乔希,我测了一下,它占用了 62% 的时间
标签: iphone objective-c cocoa-touch performance nsdate