1

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.

Community
  • 1
  • 1
HurkNburkS
  • 5,492
  • 19
  • 100
  • 183

1 Answers1

2

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];
Mick MacCallum
  • 129,200
  • 40
  • 280
  • 281
rdelmar
  • 103,982
  • 12
  • 207
  • 218
  • I thought what I did in myClass.h was creating that instance? so I can use it globally in myClass.m where as if I put **Timer *timer = [[Timer alloc] init];** in the same method as **[timer timerStart];** then I have to use **[timer stopTimer];** in the same method. – HurkNburkS Dec 10 '12 at 20:19
  • @HurkNburkS, No, in the .h you're just creating a property to point to a Timer instance, it doesn't create one. But I did have an error in my post (which I've corrected) -- when you create the instance, you should set it to the property you created, so self.timer. – rdelmar Dec 10 '12 at 22:14