[英]Objective-C: NSTimer selector
是否可以啟動計時器並通過選擇器方法傳遞多個參數?
下面是一個工作計時器的簡單示例:
gameTimer = [NSTimer scheduledTimerWithTimeInterval:0.5
target:self
selector:@selector(gameLoop:)
userInfo:nil
repeats:YES];
選擇器方法將命名為- (void)gameLoop:(NSTimer *)theTimer;
是否可以通過多個參數傳遞選擇器方法? 這樣gameLoop
方法也可以處理int
值和bool
值?
以下內容顯然不起作用,但可能會突出顯示我的追求:
gameTimer = [NSTimer scheduledTimerWithTimeInterval:0.5
target:self
selector:@selector(gameLoop:NO:75)
userInfo:nil
repeats:YES];
- (void)gameLoop:(NSTimer *)theTimer isRunning:(bool)running numberOfSteps:(int)steps;
我不同意兩個答案。 當然,您可以將所需的任何信息傳遞給NSTimer調用的方法。 那就是
userInfo
參數是為!
NSNumber *steps = [NSNumber numberWithInt: 75];
NSDictionary *info = [NSDictionary dictionaryWithObject: steps forKey: @"steps"];
//Pass any objects in a dictionary for easy extraction.
gameTimer = [NSTimer scheduledTimerWithTimeInterval:0.5
target:self
selector:@selector(gameLoop:)
userInfo: info
repeats:YES];
現在,您可以在選擇器中提取userInfo。
- (void)gameLoop:(NSTimer *)theTimer{
NSDictionary info = [theTimer userInfo];
NSInteger steps = [[info valueForKey: @"steps"] integerValue];
//etc...
}
沒有。
選擇器
計時器觸發時發送到目標的消息。 選擇器必須具有以下簽名:
- (void)timerFireMethod:(NSTimer*)theTimer
計時器將自身作為此方法的參數傳遞。
可以解決類似...
- (void)gameLoopA:(NSTimer *)theTimer {
[self gameLoop:theTimer isRunning:NO numberOfSteps:75];
}
- (void)gameLoopB:(NSTimer *)theTimer {
[self gameLoop:theTimer isRunning:NO numberOfSteps:50];
}
// etc, etc.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.