我有一个方法
-(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在我提供参数之前不会运行,否则它将打印Null值,我如何通过NSTimer调用具有参数的方法并发送这些参数呢?
答案 0 :(得分:0)
修改强>
我喜欢其他答案中提供的解决方案;传递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
调用的方法,这是计时器本身的实例。
因此,您需要考虑这些变量应该生活的位置,并且似乎使它们成为实例变量可能是最好的,可能使用类扩展。您也可以存储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];
}
使用全局变量是错误的,因为它将类的实例数限制为一个;不要这样做。
答案 1 :(得分:0)
检查以下代码,您需要更改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];
}
答案 2 :(得分:0)
我们可以这样做
-(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];
}