[英]Two parameter sets for Swift's NSTimer.scheduledTimerWithTimeInterval
[英]Using NSTimer, calling two functions with the same name, different parameters, both use scheduledTimerWithTimeInterval
我正在嘗試使用AVAudioPlayer作為助手編寫自己的淡入和淡出。
我的問題是:我有兩個名稱相同的方法定義,但一個方法使用int,另一個方法則不使用參數。 我有辦法告訴NSTimer呼叫哪一個嗎? 無法真正理解文檔:
-(void) stopWithFadeOut
{
if (_player.volume > 0.1) {
[self adjustVolume:-.1];
[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(stopWithFadeOut) userInfo:NULL repeats:NO];
}
else {
[self stop];
}
}
和
-(void) stopWithFadeOut:(NSString *)speed
{
int incr = [speed intValue];
if (_player.volume > 0.1) {
[self adjustVolume:-incr];
[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(stopWithFadeOut) userInfo:NULL repeats:NO];
}
else {
[self stop];
}
}
那些實際上有不同的名稱。 冒號是有效的,因此第二個方法的名稱(以及@selector()
的參數)為stopWithFadeOut:
。*
要創建計時器,您需要:
[NSTimer scheduledTimerWithTimeInterval:0.1
target:self
selector:@selector(stopWithFadeOut:)
userInfo:NULL //^ Note! Colon!
repeats:NO];
但是,此方法是不正確的,因為NSTimer
會將自身傳遞給其action方法。 您不可能傳遞任意對象。 這就是userInfo:
參數的作用。 您可以將一些對象附加到計時器,然后使用userInfo
方法在action方法內檢索它,如下所示:
- (void)stopWithFadeOut: (NSTimer *)tim
{
NSString * speed = [tim userInfo];
int incr = [speed intValue];
if (_player.volume > 0.1) {
[self adjustVolume:-incr];
[NSTimer scheduledTimerWithTimeInterval:0.1
target:self
selector:@selector(stopWithFadeOut:)
userInfo:speed
repeats:NO];
}
(還要注意,這意味着您的第一個方法實際上不是正確的NSTimer
操作方法,因為它沒有NSTimer
參數。)
*編譯器不會讓您在一個類中聲明或定義兩個具有相同名稱的方法,並且參數類型不計入選擇器的一部分,因此請嘗試創建-(void)dumblethwaite:(int)circumstance;
和-(void)dumblethwaite:(NSString *)jinxopotamus;
一堂課是行不通的。
這就是我想出的。 謝謝喬希。
-(void) pauseWithFadeOut
{
NSNumber *incr = [[NSNumber alloc] initWithFloat:0.1];
while (_player.volume > 0.1) {
[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(fadeOut) userInfo:incr repeats:NO];
}
}
-(void)fadeOut: (NSTimer*) deleg
{
int incr = (int) [deleg userInfo];
if (_player.volume > 0.1) {
[self adjustVolume:-incr];
}
}
-(void) pauseWithFadeOut:(NSString *)speed
{
NSNumber *incr = [[NSNumber alloc] initWithFloat:[speed floatValue]];
while (_player.volume > 0.1) {
[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(fadeOut) userInfo:incr repeats:NO];
}
[self pause];
}
-(void) stopWithFadeOut
{
NSNumber *incr = [[NSNumber alloc] initWithFloat:0.1];
while (_player.volume > 0.1) {
[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(fadeOut) userInfo:incr repeats:NO];
}
}
-(void) stopWithFadeOut:(NSString *)speed
{
NSNumber *incr = [[NSNumber alloc] initWithFloat:[speed floatValue]];
while (_player.volume > 0.1) {
[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(fadeOut) userInfo:incr repeats:NO];
}
[self stop];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.