views:

407

answers:

1

Beginner programmer. Working on a timer app.

The following applicationWillTerminate saves the state of started, stopped, startTime and stopTime and invalidates the timer. The intent is to be able to terminate application then restore state and restart timer on app restart.

//Save status to file on applicationWillTerminate.
- (void)applicationWillTerminate:(UIApplication *)application {
NSMutableArray *status = [[NSMutableArray alloc] init];
[status addObject:startTime];
[status addObject:stopTime];
[status addObject:[NSNumber numberWithInteger: started]];
[status addObject:[NSNumber numberWithInteger: stopped]];
[status writeToFile:[self statusFilePath] atomically:YES];
[status release];
if ([timer isValid]) {
    [timer invalidate];
}
[lblTimer release];
[txtDescription release];
[lblDriverName release];
[startTime release];
[stopTime release];
//  [timer release];
//  timer = nil;
}

The following viewDidLoad restores the state and is supposed to restart the timer when the if condition is met.

- (void)viewDidLoad {
// Re-direct applicationWillTerminate.
UIApplication *driverApp = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self
    selector:@selector(applicationWillTerminate:) 
    name:UIApplicationWillTerminateNotification 
    object:driverApp];
// Initialize status for first run, over-ride for saved status.
NSString *statusPath = [self statusFilePath];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:statusPath];
if (fileExists) {
    // Over-ride for status saved.
    NSArray *values = [[NSArray alloc] initWithContentsOfFile:statusPath];
    startTime = [values objectAtIndex:0];
    stopTime = [values objectAtIndex:1];
    started = [[values objectAtIndex:2] intValue];
    stopped = [[values objectAtIndex:3] intValue];
    [values release];
}
else {
    // For first run.
    started = 0;
    stopped = 0;
}
// Restart timer if previously still running.
if (started == 1 && stopped == 0) {
    if (![timer isValid]) {
        timer = [NSTimer scheduledTimerWithTimeInterval:0.25
            target:self
            selector:@selector(updateTimer)
            userInfo:nil
            repeats:YES];
    }   
}
[super viewDidLoad];
}

The program runs ok in the simulator the first time. On the second simulator run, the app crashes when it reaches the timer = [NSTimer.............repeats:YES]; statement. I have researched and tried numerous things to no avail.

Any hints would be appreciated.

A: 

if (![timer isValid]) {

change to

if (nil == timer) {

Robin
I tied your suggestion, but I got the same behavior. I went a step farther and in applicationWillTerminate changed if (![timer isValid]) {toif (!(nil == timer)) {and still got the same behavior.
Correction. Changedif (![timer isValid]) to if (nil == timer)