我的功能看起来像这样
-(void) doTransition:(id)sender withID:(int) n
如何将 int n 传递给选择器,
target:self selector:@selector(doTransition:)withID:3
这行不通
请帮忙谢谢
我的功能看起来像这样
-(void) doTransition:(id)sender withID:(int) n
如何将 int n 传递给选择器,
target:self selector:@selector(doTransition:)withID:3
这行不通
请帮忙谢谢
因此,我在 Google 上搜索了“使用参数调用选择器”并得到了一堆结果,其中第一个是关于 SO:Objective-C: Calling selectors with multiple arguments
投票最多的答案有一些细节,特别是:
[selectorTarget performSelector:mySelector withObject:@3];
这是一个简单的任务。更多信息可以在链接的问题/答案区域中找到。
注意@3
我通过了,它不是一个, int
而是一个NSNumber
。如果您有一个价值,您可以通过执行int
轻松获得。是 clang 3.4 中可用的简写语法,用于创建一个整数值。使用here 而不是很重要,因为此选择器调用需要一个类型作为参数,因此我需要一个对象,而不是原始类型(编译器是否为您自动包装,我不能说)。NSNumber
[NSNumber numberWithInt:myIntValue]
@3
NSNumber
NSNumber
int
id
withObject:
另一个重要的注意事项是定义了三个performSelector:
函数:
- (id)performSelector:(SEL)aSelector;
- (id)performSelector:(SEL)aSelector withObject:(id)anObject;
- (id)performSelector:(SEL)aSelector withObject:(id)anObject withObject:(id)anotherObject;
因此,您可以看到您可以使用不采用值的函数和采用一两个值作为选择器的函数,但除此之外,您很可能需要编写自己的逻辑来调用具有大于 2 个元数的函数。
简短的回答是你没有。performSelector: 等方法设置为将 NSObjects 作为参数传递,而不是标量值。
有一个方法 performSelector:withObject:withObject: 将调用具有 2 个对象参数的方法。
您可以通过创建 NSInvocation 来触发具有任何类型参数的方法,但这是一项相当多的工作,而且要弄清楚如何去做也有点棘手。
在您的情况下,重构您的方法以将 ID 参数作为 NSNumber 对象会更简单。
使用 NSNumber 传递值并不容易,我实现了一个将对象作为 int 传递的方法。
+ (void)showNotice:(NSString *)str atView:(UIView *)view delay:(int)delay {
[cc_message cc_instance:CC_Notice.shared method:@selector(showNotice:atView:delay:) params:str,view,Int(delay)];
}
并使用调用接收和归约为 int。
CC_Int *ccint = (CC_Int *)obj;
int value = ccint.value;
[invocation setArgument:&value atIndex:i+2];
您需要传递带有您要发送的值的 NSDictionary,例如:
NSDictionary *myDictionary = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:3] forKey:@"myInt"];