使用NSTimer,调用两个具有相同名称,不同参数的函数,都使用scheduledTimerWithTimeInterval

mat*_*dav 0 cocoa objective-c avaudioplayer ios

我正在尝试使用AVAudioPlayer作为助手编写自己的淡入淡出和淡出.

我的问题是:我有两个具有相同名称的方法定义,但一个采用int而另一个不采用参数.有没有办法让我告诉NSTimer哪一个打电话?无法理解文档:

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nstimer_Class/Reference/NSTimer.html

-(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];
}
}
Run Code Online (Sandbox Code Playgroud)

-(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];
}
}
Run Code Online (Sandbox Code Playgroud)

Jos*_*ell 7

那些实际上有不同的名字.冒号很重要,因此@selector()第二种方法的名称(以及参数)是stopWithFadeOut:.*

要创建计时器,您需要:

[NSTimer scheduledTimerWithTimeInterval:0.1 
                                 target:self 
                               selector:@selector(stopWithFadeOut:) 
                               userInfo:NULL                   //^ Note! Colon!
                                repeats:NO];
Run Code Online (Sandbox Code Playgroud)

但是,此方法不正确,因为它将自身NSTimer传递给其action方法; 传递任意对象是不可能的.这是参数的用途.您可以一些对象附加到计时器,并使用该方法在action方法中检索它,如下所示:userInfo:userInfo

- (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];
    }
Run Code Online (Sandbox Code Playgroud)

(另请注意,这意味着您的第一个方法实际上并不是一个正确的NSTimer操作方法,因为它没有NSTimer参数.)


*编译器不允许在一个类中声明或定义两个具有相同名称的方法,并且参数类型不计入选择器的一部分,因此尝试在一个类中创建-(void)dumblethwaite:(int)circumstance;-(void)dumblethwaite:(NSString *)jinxopotamus;不起作用.