【问题标题】:Invoking method via selector通过选择器调用方法
【发布时间】:2013-01-25 16:47:51
【问题描述】:

我正在用 Objective C 编写一个函数。 这就是我得到的:

int rndValue = (((int)arc4random()/0x100000000)*width);
timer1 = [NSTimer scheduledTimerWithTimeInterval:.01 
                                          target:self 
                           [self performSelector:@selector(doItAgain1:)  
                                      withObject:rndValue] 
                                        userInfo:nil
                                         repeats:YES];

选择器调用此方法并传递参数:

-(void)doItAgain1:(int)xValuex{
}

在这个阶段,顶部代码产生语法错误。 Syntax error: 'Expected ] before performSelector' 问题是什么? 最好的问候

【问题讨论】:

    标签: objective-c parameter-passing selector


    【解决方案1】:

    那行应该是这样的

    timer1 = [NSTimer scheduledTimerWithTimeInterval:.01 
             target:self selector:@selector(doItAgain1:) 
             userInfo:nil repeats:YES];
    

    您不能通过此调用发送方法参数,为此您必须执行以下操作:

    NSInvocation *inv = [NSInvocation invocationWithMethodSignature:
        [self methodSignatureForSelector:@selector(doItAgain1:)]];
    
    [inv setSelector:@selector(doItAgain1:)];
    [inv setTarget:self];
    [inv setArgument:&rndValue atIndex:2];
    
    timer1 = [NSTimer scheduledTimerWithTimeInterval:(NSTimeInterval).01 
             invocation:inv 
             repeats:YES];
    

    【讨论】:

      【解决方案2】:

      这样会更正确:

      [NSTimer scheduledTimerWithTimeInterval:.01 target:self 
                       selector:@selector(doItAgain1:)
                       userInfo:[NSNumber numberWithInt:rndValue] repeats:YES];
      

      还要注意,你以这种方式调用的选择器的语法必须是:

      - (void)doItAgain1:(NSTimer*)timer {
      
         int rndValue = [timer.userInfo intValue];
         ...
      }
      

      不可能为这样的计时器选择器指定int 参数,因此将其转换为NSNumber 对象的技巧。

      【讨论】:

      • 在 userInfo 之后的今天:您只需键入“@(rndValue)”
      • +1 @iluvcapra,但最终这取决于您所针对的 SDK...无论如何,很好解释。
      • @sergio:不,它没有。这取决于您拥有的编译器版本。
      • @newacct:我不知道为什么每个 SDK 版本都带有 Xcode 版本... :-) 但你完全正确,它是编译器...
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多