Prasad
Prasad

Reputation: 1924

How do I measure the time interval from a starting point using NSDate?

I have one method that I use in many places throughout my project that looks like the following:

-(void)showSignInView
{
    if(check for time interval)
    [[self superview] addSubview:loginController.view];
} 

I'd like to note the first time that this method is called, then on every subsequent call of this method check to make sure that the interval has been more than 15 minutes from the original call. Only then will it execute the rest of its code.

I know that you can use NSDate to measure time intervals using code like the following:

NSDate *firstTime = [[NSDate date] retain];

NSDate *SecondTime = [NSDate date];

NSLog(@"Time elapsed: %f", [SecondTime timeIntervalSinceDate:firstTime]);

but I'm not sure how to implement the initial time check, then subsequent comparisons to that time. How can I do this?

Upvotes: 1

Views: 4865

Answers (3)

CarlJ
CarlJ

Reputation: 9481

NSDate *firstTime = nil;

- (void)loadView {

    [self calculateTime:[NSDate dateWithTimeIntervalSince1970:1312996898]];
}

- (void)calculateTime:(NSDate*)secondTime
{

    double offset = [secondTime timeIntervalSinceDate:[self getFirstTime]];

    if (offset >= 900.0) {
        NSLog(@"15 min gone");
    }
}

- (NSDate *)getFirstTime
{
    if (!firstTime) {
        firstTime = [[NSDate date] retain];
    }

    return firstTime;
}

Upvotes: 2

EmptyStack
EmptyStack

Reputation: 51374

Create a property named previousTime.

@property(nonatomic, retain) NSDate *previousTime;

And create a method to find the time difference.

- (NSTimeInterval)timeDifferenceSinceLastOpen {

    if (!previousTime) self.previousTime = [NSDate date];
    NSDate *currentTime = [NSDate date];
    NSTimeInterval timeDifference =  [currentTime timeIntervalSinceDate:previousTime];
    self.previousTime = currentTime;
    return timeDifference;
}

Upvotes: 7

user23743
user23743

Reputation:

You could use GCD to achieve this. The dispatch_once() function can arrange that a block is only executed once in the lifetime of your app.

Upvotes: 3

Related Questions