IOS 如何传递变量 valet scheduledTimerWithTimeInterval

标签 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;
}

我关注了 stack overflow 中的几篇文章,但没有成功。

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

最佳答案

@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

关于IOS 如何传递变量 valet scheduledTimerWithTimeInterval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31088780/

相关文章:

iphone - 为什么 Interface Builder 不会更改我的 ViewController 类型?

ios - 在 AddressBook iOS 中根据最近使用/最常用/紧急程度对联系人进行排序

ios - App Store Connect 警告 - 文档配置无效

ios - 如何在 RxSwift 中初始化一个可观察属性?

objective-c - CSStickyHeaderFlowLayout swift

objective-c - 处理大量物体

ios - 当多个警报 View 出现在同一个 View Controller 中时,有没有办法错开?

ios - CJSON反序列化错误

iphone - Restkit 不会将对象属性插入到请求 URL 路径的路径模式中

iphone - 可拉伸(stretch)图像拉伸(stretch)部分宽于1px