我有一个方法
-(void)addFunction:(int)x andY:(int)y{
countdown--;
if(countdown == 0){
NSLog(@"Your time expired");
[myTimer invalidate];
}
else {
int c = 0;
c = x+y;
NSLog(@"%i",c);
}
}
-(void)RunTimer{
countdown = 5; //countdown has been declared as a static variable so the whole class can access it in its current state.
NSTimer * myTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(addFunction: :) userInfo:nil repeats:YES];
}
现在我的问题是,在我提供参数之前,addFunction不会运行,否则它将打印空值,我如何通过NSTimer调用一个有参数的方法并发送这些参数呢?
发布于 2014-08-11 09:20:44
编辑
我喜欢其他答案中提供的解决方案;传递userInfo
字典中的变量。然而,OP遗漏了一个基本概念,因为他不理解变量的范围,这一点在这一行的注释中揭示了出来:
countdown = 5; //countdown has been declared as a static variable so the whole class can access it in its current state.
原始答案
您只能向NSTimer
调用的方法传递一个参数,那就是计时器本身的实例。
因此,您需要考虑这些变量应该放在哪里,似乎将它们设置为实例变量可能是最好的,也许可以使用类扩展。您还可以在其中存储NSTimer
和countdown
变量:
@interface MyClass ()
{
int _x;
int _y;
NSTimer *_timer;
int _countdown;
}
...
-(void)addFunction:(NSTimer *)timer
_countdown--;
if(_countdown == 0){
NSLog(@"Your time expired");
[_timer invalidate];
}
else {
int c = 0;
c = _x + _y;
NSLog(@"%i",c);
}
}
-(void)RunTimer{
_countdown = 5;
_timer = [NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:@selector(addFunction:)
userInfo:nil
repeats:YES];
}
使用全局变量是错误的,因为它将类的实例数量限制为一个;不要这样做。
发布于 2014-08-11 09:21:49
检查以下代码,您需要更改addFunction
的方法签名并在userInfo
中传递您想要的数据
-(void)addFunction:(NSTimer *)timer{
NSDictionary *data = [timer userInfo];
NSInteger x = [data[@"x"] integerValue];
NSInteger y = [data[@"y"] integerValue];
countdown--;
if(countdown == 0){
NSLog(@"Your time expired");
[myTimer invalidate];
}
else {
int c = 0;
c = x+y;
NSLog(@"%i",c);
}
}
-(void)RunTimer{
countdown = 5; //countdown has been declared as a static variable so the whole class can access it in its current state.
NSDictionary *data = @{@"x" : @(5), @"y" : @(6)};
NSTimer * myTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(addFunction:) userInfo:data repeats:YES];
}
发布于 2014-08-11 09:26:41
我们可以简单地这样做
-(void)addFunction:(int)x andY:(int)y
{
countdown--;
if(countdown == 0)
{
NSLog(@"Your time expired");
[myTimer invalidate];
}
else {
int c = 0;
c = x+y;
NSLog(@"%i",c);
}
}
-(void)RunTimer
{
countdown = 5;
myTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(callAddFunction) userInfo:nil repeats:YES];
}
-(void)callAddFunction
{
[self addFunction:10 andY:20];
}
https://stackoverflow.com/questions/25239685
复制