在我的应用程序中,我有一段代码:
__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];
}发布于 2017-06-01 22:54:05
这有点奇怪。NSTimer保留了它的目标。也许这种情况不会因为__weak而发生,但我认为它还是发生了。*灌木*
不管是哪种情况,这听起来都像是多线程竞争条件:
最好的解决方法是让计时器保留目标对象(通过删除所有weakSelf内容)。如果计时器是重复计时器,则提供一个方法来允许处理封闭对象的代码取消该定时器,并且要小心总是调用它。
https://stackoverflow.com/questions/44318096
复制相似问题