views:

45

answers:

1

I am trying to compare two NSDates one is created by the viewDidLoad method and the other by clicking a button. I want to be able to click the button and find the time difference since the viewDidLoad was ran. I keep getting a difference of nil. Any Ideas?

#import "TimeViewController.h"

id startTime;

@implementation TimeViewController
- (void)viewDidLoad {

    NSDate *startTime = [NSDate date];
    NSLog(@"startTime = %@",startTime);
}

- (IBAction)buttonPressed{

    NSDate *now = [NSDate date];
    NSLog(@"now = %@",now);
    double timeInterval = [now timeIntervalSinceDate:startTime];
    NSLog(@"time difference = %@",[NSString stringWithFormat:@"%g",timeInterval]);

}
+3  A: 

You have

id startTime;

in the global scope, and also

    NSDate *startTime = [NSDate date];

inside viewDidLoad. The second statement creates a local variable called startTime, which hides the global variable. Use

    startTime=[[NSDate date] retain];

instead.

That said, I'd suggest you not to create the global variable. Instead, make it an instance variable and a property:

@interface TimeViewController :NSObject{
      ....
      NSDate*startDate;
}
...
@end

and as Kubi said, don't forget

-(void)dealloc{
     [startDate release];
     [super dealloc];
}

I'd also suggest not to use id to hold a known object. Who told you that? That's a very bad practice. Even when you declare a global variable, you should use

  NSDate*startDate;

so that the compiler can warn you against non-defined methods.

Yuji