2008-12-03 83 views

回答

7

您還可以使用-[NSObject performSelector:awithObject:afterDelay:]+[NSObject cancelPreviousPerformRequestsWithTarget:selector:object]

1

..

NSTimer *timer; 
當你想要安裝

..

timer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(yourMethod:) userInfo:nil repeats:NO]; 
當你想取消

..

[timer invalidate]; 
+0

不要忘記在設置時保留計時器,並在使其無效後釋放計時器。依靠運行循環爲您保留它是一種糟糕的形式,如果Apple改變了實施方式,就有破壞風險的危險。 – 2008-12-03 17:49:12

3

使用的NSTimer。用三秒鐘的時間建立方法的呼叫。它只會被調用一次:

[NSTimer scheduledTimerWithTimeInterval: 3 
            target: self 
            selector: @selector(method:) 
            userInfo: nil 
            repeats: NO]; 

方法需要看起來像這樣:

- (void) method: (NSTimer*) theTimer; 

可以傳遞參數到使用USERINFO方法(在上面設置爲例)。它可以通過[theTimer userInfo]訪問。

在NSTimer上使用無效方法取消它。

+0

方法有沒有像這樣?那麼通過NSTimer實例需要做什麼? – 2008-12-03 15:35:28

+0

我認爲我說得對,該方法確實需要看起來像這樣。 userInfo參數用於傳入額外的數據。它的訪問方式是[theTimer userInfo]。 – 2008-12-03 16:05:14