iphone - @selector 中的参数

标签 iphone cocoa cocoa-touch

有什么方法可以在选择器中传递参数吗?

示例: 我有这个方法

- (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];

其中 MyObjectmyMethod: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/

相关文章:

iphone - UILabel 文本缩放,以编程方式?

iphone - 忽略 iOS 高分辨率 @2x 文件

macos - DrawRect 和 NSProgressIndicator

ios - iOS 7 中的长屏幕标题缺少后退按钮标题

iOS 5.1 UIView调用 super ViewController的选择器

iphone - 无法在 UITableViewCell 中设置自定义背景颜色

iphone - 禁用添加到 UITableView 的 UISearchbar 的滚动

cocoa - 用新鲜的背景合成图像?

iphone - 如何扩展我检查 2 张卡是否匹配到 3 张匹配的卡的方法?

ios - 在 ios 中创建用户可配置的 UI