在@selector中使用传递的变量实现方法

时间:2015-02-10 14:36:27

标签: objective-c

这是:

distanceTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(applyShot:newPositionOne.x with:newPositionOne.y) userInfo:nil repeats:NO];

^^这不起作用。

必须等于此

[self applyShot:newPositionOne.x with:newPositionOne.y];

在运行此方法之前我基本上需要延迟,并且它传递变量,因为它们在方法运行时会有所不同,所以它必须以某种方式记住它们。

但是,我不能为我的生活弄清楚如何在@selector中传递变量。

我以前用button.tag做过,但从来没有这样做过。

任何帮助将不胜感激,谢谢。

我知道我可以设置全局变量,但是可以传递它们吗?

2 个答案:

答案 0 :(得分:2)

好的,你可以做几件事。你是对的,很难将变量传递给@selector()声明。这有两个选择:

1)调用处理变量的不同方法(在您的类中定义)。例如:

distanceTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(applyShot) userInfo:nil repeats:NO];

- (void)applyShot
{
    // manipulate variables and do your logic here
}

2)将字典传递给userInfo参数:

scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:

这本词典可能如下所示:

NSDictionary *params = @{@"newXPosition: @(90), @""newYPosition: @(100)"};

然后只需更改applyShot:方法以获取NSDictionary参数,然后在那里解析字典以查找相关值,然后“#34”应用镜头。"

答案 1 :(得分:1)

选择器不是打包方法。选择器只是消息的名称。您可以将其视为一个字符串(它曾经被实现为一个字符串)。

解决此问题的传统方法是使用NSInvocation打包完整的方法调用,而不仅仅是消息的名称。 Arguments in @selector很好地涵盖了这一点。处理它的另一种方法是将您的选项打包到userInfo并更改您的方法以从中读取其参数。

但今天通常更好的解决方案是使用dispatch_after代替:

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC),
               dispatch_get_main_queue(),
               ^(void){
                   [self applyShot:newPositionOne.x with:newPositionOne.y];
                });