以下applicationWillTerminate會保存啓動,停止,startTime和stopTime的狀態並使計時器失效。意圖是能夠終止應用程序,然後在應用程序重新啓動時恢復狀態並重新啓動計時器。NSTimer在第二次運行時崩潰iphone模擬器
//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 .............重複:YES];聲明。我已經研究並嘗試了很多事情,但無濟於事。
任何提示將不勝感激。
你隨時隨地初始化計時器?如果你可以在一個無對象上有效,我想它會給你一個例外? – lostInTransit 2010-03-05 03:38:15
代碼的其他部分初始化並使計時器失效。這些代碼部分可以在調用時多次正確運行。我沒有問題,直到我按模擬器主頁按鈕終止應用程序,然後通過選擇模擬器上的應用程序圖標重新啓動。 – user286662 2010-03-05 23:37:16
我會補充說,在第二次運行模擬器瞬間顯示xib然後閃回iphone應用程序屏幕。 – user286662 2010-03-05 23:42:52