2009-10-09 61 views
1

我正在嘗試運行下面的代碼,但在「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 

回答

4

如果您有:

startTime = [NSDate date]; 

您需要:

startTime = [[NSDate date] retain]; 

任何用alloc,new,init創建的東西都會被自動釋放(經驗法則)。所以發生了什麼是你正在創建NSDate,將它分配給startTime,它正在被自動釋放(銷燬),然後你正在試圖調用timeIntervalSinceNow在一個完全釋放的對象上,以致它爆炸了。

添加保留增加了保留計數,所以在自動釋放後它仍然存在。不要忘記,當你完成它時手動釋放它!

+0

。 「非原子的,保留」不應該照顧保留問題嗎?它與你的方法有什麼不同? – SonnyBurnette 2009-10-09 00:44:50

+0

它'應該',我不太熟悉@properties,但從我已經能夠應付的事情來看,它應該。但是在我的測試中,它沒有。我懷疑這是因爲做「startTime = [NSDate日期];」直接訪問該對象,而不是通過正在合成的setter屬性(同樣,你正在調用@synthesize,對吧?)。 雖然我的方法確實可行:-D – ACBurk 2009-10-09 01:29:39

+1

它不訪問對象,它將對象直接分配給實例變量。這就是問題所在。你不會通過該財產。 – 2009-10-10 02:54:59

3

帶你需要做@property的優勢:我更新了我的.h代碼後 self.startTime = [NSDate的日期]

+0

DOH!這很有道理。感謝您的跟進。 – SonnyBurnette 2009-10-09 01:34:50