2013年3月30日 星期六

[objective C] 定時重複執行 NSTimer


NSTimer 可以設定倒數時間, 時間到了就去把指定的方法叫起來跑,
例如說我要每 0.5 秒換一次背景顏色, 就要先定義好

1) 換顏色的方法 - (void) changeBgColorOfRootView:(NSTimer *)sender,
2) 生出一個 0.5 秒後會觸發的 NSTimer 出來,

使用的方法如下:

viewController.m : 

- (void) changeBgColorOfRootView:(NSTimer*)sender
{
    [self.view setBackgroundColor:
                          [UIColor colorWithRed: (float)rand()/RAND_MAX 
                                                    green:(float)rand()/RAND_MAX 
                                                      blue:(float)rand()/RAND_MAX 
                                                    alpha:(float)rand()/RAND_MAX ]] ;


- (void)viewDidLoad
{
 ...

    [NSTimer 
       scheduledTimerWithTimeInterval:0.5 
       target:self 
       selector:@selector(changeBgColorOfRootView:) 
       userInfo:nil 
       repeats:YES];
    
 ...    
    
}



相關說明
-----------------------------------------------------
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval) seconds
target:(id)target
selector:(SEL)aSelector
userInfo:(id)userInfo
repeats:(BOOL)repeats


Description
Creates and returns a new NSTimer object and schedules it on the current run loop in the default mode. After seconds seconds have elapsed, the timer fires, sending the message aSelector to target.


Parameters

secondsThe number of seconds between firings of the timer. If seconds is less than or equal to 0.0, this method chooses the nonnegative value of 0.1 milliseconds instead.


target
The object to which to send the message specified by aSelector when the timer fires. The target object is retained by the timer and released when the timer is invalidated.


aSelector
The message to send to target when the timer fires. The selector must correspond to a method that returns void and takes a single argument. The timer passes itself as the argument to this method.


userInfoThe user info for the timer. The object you specify is retained by the timer and released when the timer is invalidated. This parameter may be nil.


repeats
If YES, the timer will repeatedly reschedule itself until invalidated. If NO, the timer will be invalidated after it fires. Returns A new NSTimer object, configured according to the specified parameters. Availability iOS (2.0 and later)


Declared NSTimer.h Reference

沒有留言:

張貼留言