有什么方法可以在选择器中传递参数吗?
示例: 我有这个方法
- (void)myMethod:(NSString*)value1 setValue2:(NSString*)value2{
}
我需要通过传递两个参数的选择器来调用这个函数。
[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(/*my method*/) userInfo:nil repeats:YES];
我该怎么做?
最佳答案
您可以使用NSTimer
方法:
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds
invocation:(NSInvocation *)invocation
repeats:(BOOL)repeats;
相反,因为 NSInitation
对象将允许您传递参数;一个 NSInspiration
对象,如 docs定义它:
an Objective-C message rendered static, that is, it is an action turned into an object.
使用选择器创建 NSTimer
对象时,需要方法的格式为:
- (void)timerFireMethod:(NSTimer*)theTimer
NSInitation
允许您设置目标、选择器和传入的参数:
SEL selector = @selector(myMethod:setValue2:);
NSMethodSignature *signature = [MyObject instanceMethodSignatureForSelector:selector];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
[invocation setSelector:selector];
NSString *str1 = @"someString";
NSString *str2 = @"someOtherString";
//The invocation object must retain its arguments
[str1 retain];
[str2 retain];
//Set the arguments
[invocation setTarget:targetInstance];
[invocation setArgument:&str1 atIndex:2];
[invocation setArgument:&str2 atIndex:3];
[NSTimer scheduledTimerWithTimeInterval:0.1 invocation:invocation repeats:YES];
其中 MyObject
是 myMethod:setValue2:
声明和实现的类 - instanceMethodSignatureForSelector:
是在 上声明的便利函数>NSObject
为您返回一个 NSMethodSignature
对象,并将其传递给 NSInitation
。
另外,要注意,使用 setArgument:atIndex:
时,要传递给作为选择器设置的方法的参数索引从索引 2 开始。来自文档:
Indices 0 and 1 indicate the hidden arguments self and _cmd, respectively; you should set these values directly with the setTarget: and setSelector: methods. Use indices 2 and greater for the arguments normally passed in a message.
关于iphone - @selector 中的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1349740/