@selector 中的参数 [英] Arguments in @selector
问题描述
有什么办法可以在选择器中传递参数吗?
Is there any way that I can pass arguments in selector?
示例:我有这个方法
- (void)myMethod:(NSString*)value1 setValue2:(NSString*)value2{
}
我需要通过传递两个参数的选择器来调用这个函数.
and I need to call this function through a selector passing two arguments.
[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;
相反,由于 NSInvocation
对象将允许您传递参数;NSInvocation
对象是,作为 docs 定义它:
Instead, since an NSInvocation
object will allow you to pass arguments; an NSInvocation
object is, as the docs define it:
Objective-C 消息呈现静态,也就是说,它是一个动作变成了一个对象.
an Objective-C message rendered static, that is, it is an action turned into an object.
虽然使用选择器创建 NSTimer
对象需要方法的格式是:
Whilst creating an NSTimer
object using a selector requires the format of the method being:
- (void)timerFireMethod:(NSTimer*)theTimer
NSInvocation
允许您设置目标、选择器和传入的参数:
An NSInvocation
allows you to set the target, the selector, and the arguments that you pass in:
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
对象,传递给 NSInvocation
.
Where MyObject
is the class that myMethod:setValue2:
is declared and implemented on – instanceMethodSignatureForSelector:
is a convenience function declared on NSObject
which returns an NSMethodSignature
object for you, to be passed to NSInvocation
.
另外,请注意,使用 setArgument:atIndex:
,要传递给设置为选择器的方法的参数的索引从索引 2 开始.来自文档:
Also, to note, with setArgument:atIndex:
, the indices for arguments to be passed to the method set as the selector start at index 2. From the docs:
索引0和1分别表示隐藏参数self和_cmd;您应该直接使用 setTarget: 和 setSelector: 方法设置这些值.对通常在消息中传递的参数使用索引 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.
这篇关于@selector 中的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!