如何通过选择器方法传递int值?

Emo*_*mon 10 objective-c type-conversion selector ios

我想int从我的selector方法传递一个值,但是selector方法只接受一个对象类型参数.

int y =0;
[self performselector:@selector(tabledata:) withObject:y afterDelay:0.1];
Run Code Online (Sandbox Code Playgroud)

方法执行在这里

-(int)tabledata:(int)cellnumber {
   NSLog(@"cellnumber: %@",cellnumber);
   idLabel.text = [NSString stringWithFormat:@"Order Id: %@",[[records objectAtIndex:cellnumber] objectAtIndex:0]];
}
Run Code Online (Sandbox Code Playgroud)

但是我的方法中没有得到确切的整数值,我只得到id值.

Ade*_*edt 19

如果你拥有'目标选择器,最简单的解决方案是将int参数包装在NSNumber中:

-(int)tabledata:(NSNumber *)_cellnumber {
    int cellnumber = [_cellnumber intValue];
    ....
}
Run Code Online (Sandbox Code Playgroud)

要调用此方法,您将使用:

[self performselector:@selector(tabledata:) withObject:[NSNumber numberWithInt:y] afterDelay:0.1];
Run Code Online (Sandbox Code Playgroud)


Bjö*_*ser 15

这也适用于int参数,如果您无法更改要执行的选择器的签名,则该参数特别有用.

SEL sel = @selector(tabledata:);

NSMethodSignature *signature = [[self class] instanceMethodSignatureForSelector:sel];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
invocation.selector = sel;
// note that the first argument has index 2!
[invocation setArgument:&y atIndex:2];

// with delay
[invocation performSelector:@selector(invokeWithTarget:) withObject:self afterDelay:0.1];
Run Code Online (Sandbox Code Playgroud)