[英]NSTimer crashes iphone simulator on second run
以下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 ............. repeats:YES]時崩潰。 聲明。 我已經研究並嘗試了無數次嘗試。
任何提示將不勝感激。
if (![timer isValid]) {
改成:
if (nil == timer) {
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.