以下applicationWillTerminate保存启动,停止,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 .............重复:是];声明。我已经研究并尝试了许多无用的东西。
任何提示都将不胜感激。
答案 0 :(得分:0)
if (![timer isValid]) {
更改为:
if (nil == timer) {