objective-c - 使用NSTimer,调用两个同名不同参数的函数,都使用scheduledTimerWithTimeInterval

标签 objective-c ios cocoa avaudioplayer

我正在尝试使用 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];
}
}

-(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自身 传递给它的操作方法;您不可能传入任意对象。这就是 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];
    }

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


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

关于objective-c - 使用NSTimer,调用两个同名不同参数的函数,都使用scheduledTimerWithTimeInterval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10760901/

相关文章:

iphone - iOS 中 X.509 ASN.1 RSA 公钥的 SecKeyRef

cocoa - NSButton 具有可变大小宽度、圆角

objective-c - Shell脚本语法高亮库

ios - initWithCoder 在 ios 中显示错误的帧

ios - UILabel 文字一一淡出

ios - 收到电子邮件结果后执行Segue

iphone - 将 nsstring 转换为 NSMutableDictionary

objective-c - NSView 约束 - 如何强制 subview 的纵横比保持不变?

iphone - 是时候为 Apple 不可知论者学习 Objective-C/Cocoa

ios - 我怎样才能让我的 UISwitch 调用方法(我正在使用 theos)