在 iOS 开发中,使用 NSTimer 时很容易出现循环引用的问题,解决这个问题可以使用如下两种方法:

  1. 使用弱引用:将 NSTimer 的 target 设置为一个弱引用对象,通常会使用一个中间对象来持有弱引用。
__weak typeof(self) weakSelf = self;
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:[WeakProxy proxyWithTarget:self] selector:@selector(timerAction) userInfo:nil repeats:YES];

中间对象 WeakProxy 的实现如下:

@interface WeakProxy : NSProxy

@property (nonatomic, weak, readonly) id target;

+ (instancetype)proxyWithTarget:(id)target;

@end

@implementation WeakProxy

+ (instancetype)proxyWithTarget:(id)target {
    WeakProxy *proxy = [WeakProxy alloc];
    proxy->_target = target;
    return proxy;
}

- (nullable NSMethodSignature *)methodSignatureForSelector:(SEL)sel {
    return [_target methodSignatureForSelector:sel];
}

- (void)forwardInvocation:(NSInvocation *)invocation {
    [invocation invokeWithTarget:_target];
}

@end
  1. 使用 block 回调:将 NSTimer 的 target 设置为 nil,然后使用 block 来处理定时器的回调逻辑。
__weak typeof(self) weakSelf = self;
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
    [weakSelf timerAction];
}];

在上述两种方法中,通过使用弱引用或 block 回调,可以避免循环引用的问题,确保定时器能够正常释放。

iOS 开发 - 解决 NSTimer 循环引用问题

原文地址: https://www.cveoy.top/t/topic/hWIL 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录