美文网首页
NSTimer 解决循环引用问题

NSTimer 解决循环引用问题

作者: 曾柏超 | 来源:发表于2020-02-16 16:10 被阅读0次

解决方法 : Proxy + 消息转发

截屏2020-02-16下午4.07.38.png
#import "ViewController.h"
#import "MJProxy.h"
@interface ViewController ()
 
@property(nonatomic,strong)NSTimer *timer;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //  NSTimer
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:[MJProxy proxyWithTarget:self] selector:@selector(testLink) userInfo:nil repeats:YES];
     
}

- (void)testLink{
    NSLog(@"%s",__func__);
}

- (void)dealloc{
    
    NSLog(@"%s",__func__);
     
    [self.timer invalidate];
}

@end
#import <Foundation/Foundation.h>

 
@interface MJProxy : NSObject

+ (instancetype)proxyWithTarget:(id)target;
@property(weak, nonatomic) id target;

@end





#import "MJProxy.h"

@implementation MJProxy
+ (instancetype)proxyWithTarget:(id)target
{
    MJProxy *proxy = [[MJProxy alloc] init];
    proxy.target = target;
    return proxy;
}

//消息转发
- (id)forwardingTargetForSelector:(SEL)aSelector
{
    return self.target;
}


@end

相关文章

网友评论

      本文标题:NSTimer 解决循环引用问题

      本文链接:https://www.haomeiwen.com/subject/nownectx.html