IOS如何传递可变代客的scheduledTimerWithTimeInterval

时间:2015-06-27 12:30:41

标签: ios objective-c iphone nstimer

我通过Web服务将用户位置发送到服务器,在响应中我得到间隔以发送下一个位置。我正在使用以下调用使用计时器发送位置,但是当我得到不同的值时,计时器仍然使用旧值。我还尝试使计时器无效以设置新值,但似乎无法正常工作

我有全局变量

long counter= 10;


self.timer = [NSTimer scheduledTimerWithTimeInterval:counter target:self selector:@selector(updateLocation) userInfo:nil repeats:YES];

- (void)updateLocation {
CLLocation *location = self.locationManager.location;
....
counter = 30;
}

我从堆栈溢出跟踪了几个帖子,但没有让它工作。

简而言之,我需要根据回复发送更新的位置!

1 个答案:

答案 0 :(得分:2)

@interface MyClass()

@property (strong, nonatomic) NSTimer *timer;
@property (nonatomic) CGFloat counter;

@end

@implementation MyClass

- (void)viewDidLoad
{
    [super viewDidLoad];

    //set initial value for timer
    self.counter = 10;
    [self resetTimer];
}

//...
- (void)resetTimer
{
    [self.timer invalidate]
    self.timer = [NSTimer scheduledTimerWithTimeInterval:self.counter target:self selector:@selector(updateLocation) userInfo:nil repeats:NO];
}

- (void)updateLocation 
{
    CLLocation *location = self.locationManager.location;
    //...
    self.counter = 30;
    [self resetTimer];
}
//...
- (void)dealloc
{
    //invalidate timer to avoid zombie objects  (EXC_BAD_ACCESS crash)
    [self.timer invalidate];
}
@end