內存管理:CADisplayLink、NSTimer使用注意 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 <Foundation/Foundation.h>

@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];
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章