解决NSTimer循环引用问题(消息转发)

两种创建方式

第一种

- (void)viewDidLoad {
    [super viewDidLoad];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
        NSLog(@"hello...");
    }];
}
-(void)dealloc
{
    NSLog(@"secondVC 销毁");
    [self.timer invalidate];
    self.timer = nil;
}

2019-08-27 17:25:48.894257+0800 PerformanceMonitor[5904:139667] hello...
2019-08-27 17:25:49.894237+0800 PerformanceMonitor[5904:139667] hello...
2019-08-27 17:25:50.894200+0800 PerformanceMonitor[5904:139667] hello...
2019-08-27 17:25:51.893616+0800 PerformanceMonitor[5904:139667] hello...
2019-08-27 17:25:52.414153+0800 PerformanceMonitor[5904:139667] secondVC 销毁

第二种

- (void)viewDidLoad {
    [super viewDidLoad];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(action) userInfo:nil repeats:YES];
}
-(void)action
{
    NSLog(@"hello...");
}

2019-08-27 17:25:48.894257+0800 PerformanceMonitor[5904:139667] hello...
2019-08-27 17:25:49.894237+0800 PerformanceMonitor[5904:139667] hello...
2019-08-27 17:25:50.894200+0800 PerformanceMonitor[5904:139667] hello...
2019-08-27 17:25:51.893616+0800 PerformanceMonitor[5904:139667] hello...
......................................(不销毁)

如何解决该问题

方法一、

__weak typeof(self) weakSelf = self;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:weakSelf selector:@selector(action) userInfo:nil repeats:YES];

此方法并无效

方法二、

创建一个中间代理类
WeakProxy

#import 

@interface WeakProxy : NSProxy
+ (instancetype)proxyWithTarget:(id)target;
@end
#import "WeakProxy.h"
@interface WeakProxy ()
@property (nonatomic, weak) id weakTarget;
@end
@implementation WeakProxy
+ (instancetype)proxyWithTarget:(id)target {
    return [[self alloc] initWithTarget:target];
}

- (instancetype)initWithTarget:(id)target {
    _weakTarget = target;
    return self;
}

- (id)forwardingTargetForSelector:(SEL) aSelector
{
    //接受者重定向(第二次机会)
    if ([self.weakTarget respondsToSelector:aSelector]) {
        return self.weakTarget;
    }
    else
    {
        NSLog(@"该方法未实现");
        return nil;
    }
}
@end

使用

self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:[WeakProxy proxyWithTarget:self] selector:@selector(action) userInfo:nil repeats:YES];

解决~

你可能感兴趣的:(解决NSTimer循环引用问题(消息转发))