【问题标题】:How to call parameterized method with more than 2 parameters to the selector [duplicate]如何将具有超过2个参数的参数化方法调用到选择器[重复]
【发布时间】:2012-12-04 12:39:33
【问题描述】:

可能重复:
Arguments in @selector

如何向选择器调用参数化方法超过2个参数, 说EX我有这样的方法

-(void)GetTheData:(NSString *)str1 :(NSString *)str2

现在我需要在@selector 内的以下计时器中调用此方法。我该如何调用??

NSTimer  *timer = [NSTimer scheduledTimerWithTimeInterval:0.0 target:self selector:@selector(**HowCanICallHere**) userInfo:nil repeats:YES];

【问题讨论】:

  • 使用这种风格的函数名是不好的做法。您应该为函数的每个部分命名。在您的示例中,没有真正的方法可以知道 str2 是什么或可以从中获得什么样的数据。

标签: iphone objective-c ios xcode selector


【解决方案1】:

NSDictionary作为参数传递给目标方法

 NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"1",@"parameter1",@"2",@"parameter2", nil];

        [ NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(myFunction:) userInfo: dictionary repeats:NO];

进一步检索目标函数中的参数

-(void)myFunction:(NSTimer *)timer{
    NSLog(@" dict : %@",timer.userInfo);
}

这样你可以通过在NSDictionary中添加更多的keyValue对来传递多个参数

【讨论】:

    【解决方案2】:

    我不确定你能做到。出于同样的原因,我们提供了“userInfo”选项,以传递多个参数。您可以通过创建一个包含两个对象的字典来轻松实现它:

    NSDictionary *dict = [NSDictionary dictionaryWithObjects:objArray andKeys:keyArray];
    

    并将该字典作为 userInfo 对象传递给方法:

    NSTimer  *timer = [NSTimer scheduledTimerWithTimeInterval:0.0 target:self selector:@selector(urTimerMethod:) userInfo:dict repeats:YES];
    

    将方法定义为:

    - (void)urTimerMethod:(NSTimer *)timer {
            NSDictionary *dict = [timer userInfo];
    }
    

    【讨论】:

      【解决方案3】:

      你可以用这个:

      NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.0 target:self 选择器:@selector(GetTheData::) userInfo:nil repeats:YES];

      【讨论】:

      • 如何按照 sujay 的要求在此方法中传递两个以上的参数?
      • Atif,我只是展示了我们如何将选择器用于多个参数。现在,您的查询是什么?
      • 你读过这个问题吗?
      • Atif,因为 userInfo 是 'id' 类型,所以我们可以尽可能多地发送两个逗号分隔的对象。让我为此工作。我相信它会起作用的。我从不在 NSTimer 中使用多参数选择器,但通常我已经使用了很多次。:)
      • 是的,我读过他在问两个如何使选择器具有两个参数..:)
      【解决方案4】:

      我知道如何将它与执行选择器一起使用,所以也许您可以通过以下方式进行操作:

      -(void)GetTheData1:(NSString *)str1 GetTheData2:(NSString *)str2
      
      NSTimer  *timer = [NSTimer scheduledTimerWithTimeInterval:0.0 target:self selector:@selector(mymethod) userInfo:nil repeats:YES];
      
      - (void) mymethod {
      [self performSelector:@selector(GetTheData1:GetTheData2:) withObject:str1 withObject:str2];
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-03-13
        • 2012-04-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-22
        • 1970-01-01
        相关资源
        最近更新 更多