Search code examples
iphoneobjective-cnsstringxcode4

iphone - difference between time(app hiding) and time(app appearing)


how do i get the date from appEnterBackground and take away from appEnterForeground, then show the difference in a label. This is my code so far..

**.h**
    NSTimeInterval appEnteredBackground;
    NSTimeInterval appEnteredForeground;
    NSTimeInterval difference;  

**.m**

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    appEnteredBackground = [NSDate timeIntervalSinceReferenceDate];
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    appEnteredForeground = [NSDate timeIntervalSinceReferenceDate];
    difference = appEnteredForeground - appEnteredBackground;

    NSLog(@"Duration is %@",[NSDate dateWithTimeIntervalSinceReferenceDate: difference]);
    NSLog(@"Duration is %@", [NSString stringWithFormat:@"%f", difference]);

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];

    NSString *time = [NSString stringWithFormat:@"%f", difference];   **//ERROR HERE (variable not used)**

    [dateFormatter release];
}

Any help would be fantastic


Solution

  • I think that you do not have errors here. You are correctly calculating the time difference, then you build a string with its "description" but do not use it.

    To see if it all works correctly try this before the end of the method:

    NSLog(@"Computed time was: %@", time);
    

    You should care about that time variable, since you are not actively using it.