所以我使用Brock Wolfs答案来计算我的应用程序中的操作。实际上甚至我的时间是从我使用
发送请求到我的服务器NSURLConnection
直到我完成从
中的请求下载所有数据后的那一刻connectionDidFinishLoading
然而,由于一些奇怪的原因,这个解决方案无法正常工作,它会以0.00秒的速度继续回复..即使实际事件使用断点大约需要8秒。
这是我的Brock代码版本(精确副本)
Timer.h
#import <Foundation/Foundation.h>
@interface Timer : NSObject{
NSDate *start;
NSDate *end;
}
- (void) startTimer;
- (void) stopTimer;
- (double) timeElapsedInSeconds;
- (double) timeElapsedInMilliseconds;
- (double) timeElapsedInMinutes;
@end
Timer.m
#import "Timer.h"
@implementation Timer
- (id) init {
self = [super init];
if (self != nil) {
start = nil;
end = nil;
}
return self;
}
- (void) startTimer {
start = [NSDate date];
}
- (void) stopTimer {
end = [NSDate date];
}
- (double) timeElapsedInSeconds {
return [end timeIntervalSinceDate:start];
}
- (double) timeElapsedInMilliseconds {
return [self timeElapsedInSeconds] * 1000.0f;
}
- (double) timeElapsedInMinutes {
return [self timeElapsedInSeconds] / 60.0f;
}
@end
然后在课堂上我想用它
myClass.h
#import "Timer.h"
Timer *timer;
//..
@property (strong, nonatomic) Timer *timer;
myClass.m
@synthesize timer;
//..
- (IBAction)vehicleSearchRequest:(NSData *)postBodyData
{
//..
[timer startTimer];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
//..
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//..
[timer stopTimer]; // comes back as 0.000
NSLog(@"Total time was: %lf milliseconds", [timer timeElapsedInMilliseconds]);
//..
}
任何帮助将不胜感激。
答案 0 :(得分:2)
它不起作用的原因并不奇怪。您从未创建过Timer实例。在[timer timerStart]之前插入此行:
self.timer = [[Timer alloc] init];