2011-08-17 73 views
0

我有一個功能可以說的OnTimer如何處理多個NSTimer?

-(void)onTimer { 
     * Some Operation * 
} 

我想調用這個方法就像這樣......

在10秒應該每隔0.2秒致電....然後在另一10秒,調用此方法的持續時間應該增加.....通過這樣做,它將顯示操作從快速模式變得緩慢......並且它將在最後停止。

請指導。

回答

1

我覺得這是很容易做到與2個定時器。在h文件,聲明2個定時器:

float intervalYouWant; 
NSTimer * timer1; 
NSTimer * timer2; 

在.m文件,

- (void)viewDidLoad; { 
    intervalYouWant = 0.2; 
    timer1 = [NSTimer scheduledTimerWithTimeInterval:intervalYouWant target:self selector:@selector(methodForTimer1) userInfo:nil repeats:YES]; 
    timer2 = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(changeTimer1) userInfo:nil repeats:YES]; 
} 

- (void)changeTimer1; { 
    [timer1 invalidate]; 
    timer1 = nil; 
    intervalYouWant += amountYouWantToAdd; 
    timer1 = [NSTimer scheduledTimerWithTimeInterval:intervalYouWant target:self selector:@selector(methodForTimer1) userInfo:nil repeats:YES]; 
} 

這應該取消所述第一計時器每10秒,並用新的時間間隔重新啓動它。不要忘記使dealloc方法中的定時器無效。希望有所幫助!

0

開始在非重複模式定時器

float interval = 0.2; //global variable 

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

.......... 
.......... 

-(void) timerSelector:(NSTimer *)timer{ 
    static float timeConsumed = 0.0; 
    //do your task which you want to do here 
    ............ 
    ............ 

// in the end 
    if(timeConsumed > 10.0){ 
    interval = 0.5; //increase the interval so it decrease the speed.. 
    }else if(timeConsumed > 20.0){ 
    interval = 1.0; 
    }... go on like this until you stop it.. 

    timeConsumed += interval; 
    [NSTimer scheduledTimerWithTimeInterval:interval target:self selector:@selector(timerSelector:) userInfo:nil repeats:NO]; 
} 

書面memory..So語法錯誤possible..Correct yourself..hope這有助於..

+0

我已經在你的代碼中輸入了這些值float intervalYouWant = 0.2; float amountYouWantToAdd = 0.5;但它不能正常工作......它只是在無限的時間內以0.2的速度繼續運行......它沒有增加時間,並且在幾次之後不會停止。我的任務是在啓動時快速調用該方法,並在某些perioid後減速...就像Casino Scroll – Tariq

+0

然後用您的代碼編輯您的問題。也可以在其中設置可變間隔... timeConsumed應該是靜態變量 – Krishnabhadra