Reputation: 5510
So I am using Brock Wolfs answer to timing an action in my application. The actual even I am timing is from when I send a request to my server using
NSURLConnection
Till the moment once I have finished downloading all of the data from that requestion in
connectionDidFinishLoading
However for some weird reason this solution is not working, it keeps replying with 0.00 seconds.. even though the actual event takes about 8seconds using break points.
This is my version of Brock's code (exact copy)
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
Then in the class I want to use it
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]);
//..
}
any help would be greatly appreciated.
Upvotes: 1
Views: 551
Reputation: 104082
The reason it's not working isn't weird at all. You never created a Timer instance. Insert this line just before [timer timerStart]:
self.timer = [[Timer alloc] init];
Upvotes: 2