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 应用的 AppStore 安装

objective-c - UIViewController 的默认 View (如 UIScrollView)- 无法设置其内容偏移量

iphone - ASIHTTPRequest 随每个请求发送数据

iphone - EKEventEditViewController 本地化

iphone - 我有一个在后台播放音频的 iPad 应用程序,但应用程序图标没有出现在 ipod 控件中

xml - 在 Cocoa 中使用 xsd 文件验证 XML 模式?

iphone - Foundation Framework 中我的 iPhone 上的应用程序列表

objective-c - 如何在cocoa中选择文件

objective-c - 我如何将工作日添加到 NSDate?

ios - 使用 Swift 重建现有应用程序