【问题标题】:How do I pass an argument to @selector()?如何将参数传递给@selector()?
【发布时间】:2011-07-09 00:29:28
【问题描述】:

我有以下 NSTimer 调用

[NSTimer scheduledTimerWithTimeInterval:2.0
                               target:self
                             selector:@selector(panelVisibility:)
                             userInfo:nil
                              repeats:NO];

-(void)panelVisibility:(BOOL)visible{
...
}

我需要将 BOOL 值传递给 panelVisibility 方法。如何指定参数值?

【问题讨论】:

标签: objective-c


【解决方案1】:

在这种情况下,你没有。查看reference docs

选择器
计时器触发时发送给目标的消息。这 选择器必须具有以下内容 签名:

  • (void)timerFireMethod:(NSTimer*)theTimer

计时器将自己作为 此方法的参数。

所以你的panelVisibility: 方法可以接受的唯一参数是NSTimer*,计时器会自动为你传递这个参数。

但是,您可以使用userInfo 字段传递您想要的任何其他信息。例如,您可以这样做:

[NSTimer scheduledTimerWithTimeInterval:2.0
                               target:self
                               selector:@selector(panelVisibility:)
                               userInfo:[NSNumber numberWithBool: myBool]
                               repeats:NO];

...然后有:

-(void)panelVisibility:(NSTimer*)theTimer{
    BOOL visible = [theTimer.userInfo boolValue];
    //...
}

【讨论】:

    【解决方案2】:

    你不能那样做。请注意,docs 表示该方法必须具有以下签名:

    - (void)timerFireMethod:(NSTimer*)theTimer
    

    使用userInfo 参数传递[NSNumber nnumberWithBool:bool] 并通过调用来检索它:

    BOOL isSomething = [[theTimer userInfo] boolValue];
    

    在触发时计时器调用的方法内部。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-25
      • 1970-01-01
      • 2010-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-09
      相关资源
      最近更新 更多