【发布时间】:2017-06-01 22:31:00
【问题描述】:
在我的应用程序中,我有以下一段代码:
__weak __typeof(self)weakSelf = self;
_pingTimer = [NSTimer scheduledTimerWithTimeInterval:5.0
repeats:YES
block:^(NSTimer * _Nonnull timer)
{
__strong __typeof(weakSelf)strongSelf = weakSelf;
[strongSelf pingWithBlock:nil];
}];
这在 iOS 10+ 中完美运行,但我需要该应用程序也支持 iOS 9。所以我需要提供一种对两者都适用的方法。
我试过了:
__weak __typeof(self)weakSelf = self;
_pingTimer = [NSTimer scheduledTimerWithTimeInterval:5.0
target:weakSelf
selector:@selector(pingWithBlock:)
userInfo:nil
repeats:YES];
pingWithBlock 方法在同一个类中定义,它是一个实例方法。
但这似乎不起作用,这意味着我遇到了糟糕的内存访问崩溃。
如果有人有任何建议,我们将不胜感激。
编辑: 感谢@dgatwood 解释下面的代码解决了这个问题
- (void)autoPing
{
_pingTimer = [NSTimer scheduledTimerWithTimeInterval:self.autoCheckInterval
target:self
selector:@selector(pingWithBlock)
userInfo:nil
repeats:YES];
}
-(void)pingWithBlock
{
[self pingWithBlock:nil];
}
【问题讨论】:
-
您的
pingWithBlock:方法在哪里?并定义“不起作用”。 -
刚刚更新了我的问题
-
不要用答案编辑你的问题。发布实际答案。
标签: ios objective-c block nstimer