次の 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];
}
プログラムは、シミュレーターで初めて正常に実行されます。2 回目のシミュレーターの実行で、タイマー = [NSTimer.............repeats:YES] に達するとアプリがクラッシュします。声明。色々と調べて試してみましたがダメでした。
ヒントをいただければ幸いです。