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]);
}
You have
in the global scope, and also
inside
viewDidLoad. The second statement creates a local variable calledstartTime, which hides the global variable. Useinstead.
That said, I’d suggest you not to create the global variable. Instead, make it an instance variable and a property:
and as Kubi said, don’t forget
I’d also suggest not to use
idto hold a known object. Who told you that? That’s a very bad practice. Even when you declare a global variable, you should useso that the compiler can warn you against non-defined methods.