我正在嘗試運行下面的代碼,但在「Tick」被寫入控制檯後,它會一直鎖定我的模擬器。它永遠不會輸出「Tock」,所以我的猜測是它必須處理「NSTimeInterval elapsedTime = [startTime timeIntervalSinceNow];」 IBactions由按鈕激活。 timer和startTime在.h中分別定義爲NSTimer和NSDate。NSTimer問題
誰能告訴我我做錯了什麼?
代碼:
- (IBAction)startStopwatch:(id)sender
{
startTime = [NSDate date];
NSLog(@"%@", startTime);
timer = [NSTimer scheduledTimerWithTimeInterval:1 //0.02
target:self
selector:@selector(tick:)
userInfo:nil
repeats:YES];
}
- (IBAction)stopStopwatch:(id)sender
{
[timer invalidate];
timer = nil;
}
- (void)tick:(NSTimer *)theTimer
{
NSLog(@"Tick!");
NSTimeInterval elapsedTime = [startTime timeIntervalSinceNow];
NSLog(@"Tock!");
NSLog(@"Delta: %d", elapsedTime);
}
我在.H如下:
@interface MainViewController : UIViewController <FlipsideViewControllerDelegate> {
NSTimer *timer;
NSDate *startTime;
}
- (IBAction)startStopwatch:(id)sender;
- (IBAction)stopStopwatch:(id)sender;
- (void)tick:(NSTimer *)theTimer;
@property(nonatomic, retain) NSTimer *timer;
@property(nonatomic, retain) NSDate *startTime;
@end
。 「非原子的,保留」不應該照顧保留問題嗎?它與你的方法有什麼不同? – SonnyBurnette 2009-10-09 00:44:50
它'應該',我不太熟悉@properties,但從我已經能夠應付的事情來看,它應該。但是在我的測試中,它沒有。我懷疑這是因爲做「startTime = [NSDate日期];」直接訪問該對象,而不是通過正在合成的setter屬性(同樣,你正在調用@synthesize,對吧?)。 雖然我的方法確實可行:-D – ACBurk 2009-10-09 01:29:39
它不訪問對象,它將對象直接分配給實例變量。這就是問題所在。你不會通過該財產。 – 2009-10-10 02:54:59