[英]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.