我正在研究一個應用程序,我想每隔幾秒鐘調用一個方法,同時用戶將他們的手指放在按鈕上,並在發佈時停止。在iOS中的Touch Down上觸發重複事件
目前,我正在觸發事件中啓動一個NSOperation,然後應該調用NSTimer在2秒後觸發另一個NSOperation。
但是隻有第一個「runOperation」正在發生;來自計時器的人不是。
- (IBAction)buttonPressed:(id)sender
{
[self doStuff];
}
- (void)runOperation {
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self
selector:@selector(doStuff)
object:nil];
[queue addOperation:operation];
[operation release];
}
- (void)doStuff {
/* stuff goes here */
[self performSelectorOnMainThread:@selector(setTimer) withObject:nil waitUntilDone:YES];
}
- (void)setTimer
{
timer = [[NSTimer timerWithTimeInterval:2.f target:self selector:@selector(runOperation) userInfo:nil repeats:NO] retain];
}
- (IBAction)finishTakingPictures:(id)sender {
[timer invalidate];
timer = nil;
}
doh doh and doh again;我怎麼錯過了將定時器添加到runloop的問題!是的,很多不必要的間接方法(導致大量關於未能看到真正問題的麻煩,並且在主線程上設置計時器正在抓着吸管)。 – akbsteam
感謝您的詳細回覆,如果可以的話我會接受這兩個答覆,但是NJones可能更接近我將使用的實現。這就是說,總是很高興看到另一種方法。 – akbsteam
很高興你在學習。 WRT SO,一些想法。一般來說,你應該接受第一個正確的答案,除非後面的答案要優越得多。我不在乎幾點,原則上這樣說。我的回答是正確的,我告訴過你如何解決這個問題。所有額外的東西都是肉汁。 @NJones的回答很好,這只是我的一個小小的調整。在這種情況下,沒關係,但有時候你不想使用視圖屬性來跟蹤狀態(例如,當視圖可能會在操作仍在進行時消失)。最後,你可以儘可能多的答覆,只要你喜歡。快樂的編碼。 – XJones