1

下面的applicationWillTerminate 保存started、stopped、startTime 和stopTime 的状态并使定时器失效。目的是能够终止应用程序,然后在应用程序重新启动时恢复状态和重新启动计时器。

//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;
}

下面的 viewDidLoad 恢复状态,应该在满足 if 条件时重新启动计时器。

- (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];
}

程序第一次在模拟器中运行正常。在第二次模拟器运行时,应用程序在达到计时器时崩溃 = [NSTimer......repeats:YES]; 陈述。我研究并尝试了很多东西都无济于事。

任何提示将不胜感激。

4

1 回答 1

0
if (![timer isValid]) {

改成:

if (nil == timer) {
于 2010-03-05T05:04:03.607 回答