内存管理:CADisplayLink、NSTimer使用注意

CADisplayLink、NSTimer使用注意

CADisplayLink、NSTimer会对target产生强引用,如果target又对它们产生强引用,那么就会引发循环引用

  • 解决方案
  • 使用block
    __weak typeof(self) weakSelf = self;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
        [weakSelf timerTest];
    }];
  • 使用代理对象(NSProxy)
#import 

@interface WDProxy : NSObject
+ (instancetype)proxyWithTarget:(id)target;
@property (weak, nonatomic) id target;
@end
#import "WDProxy.h"

@implementation WDProxy

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

- (id)forwardingTargetForSelector:(SEL)aSelector
{
    return self.target;
}

@end

或者继承NSProxy,使用效率更高



@interface WDProxy : NSProxy
+ (instancetype)proxyWithTarget:(id)target;
@property (weak, nonatomic) id target;
@end

#import "WDProxy.h"

@implementation WDProxy

+ (instancetype)proxyWithTarget:(id)target
{
    // NSProxy对象不需要调用init,因为它本来就没有init方法
    WDProxy *proxy = [WDProxy alloc];
    proxy.target = target;
    return proxy;
}

- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel
{
    return [self.target methodSignatureForSelector:sel];
}

- (void)forwardInvocation:(NSInvocation *)invocation
{
    [invocation invokeWithTarget:self.target];
}
@end

使用

self.link = [CADisplayLink displayLinkWithTarget:[WDProxy proxyWithTarget:self] selector:@selector(linkTest)];
    [self.link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:[WDProxy proxyWithTarget:self] selector:@selector(timerTest) userInfo:nil repeats:YES];

你可能感兴趣的:(内存管理:CADisplayLink、NSTimer使用注意)