利用NSProxy解决NSTimer内存泄漏问题

在iOS开发中经常使用到NSTimer,我们都知道NSTimer会对target retain一次,导致相互强引用target无法释放。我们可以消息转发代理NSProxy来解决NSTimer内存泄漏问题。
具体代码如下:

#import 

@interface TTWeakProxy : NSProxy

+ (instancetype)weakProxyWithTarget:(id)target;

@end
#import "TTWeakProxy.h"

@interface TTWeakProxy ()

@property (nonatomic, weak) id target;

@end

@implementation TTWeakProxy

+ (instancetype)weakProxyWithTarget:(id)target
{
    TTWeakProxy *weakProxy = [TTWeakProxy alloc];
    weakProxy.target = target;
    
    return weakProxy;
}

- (id)forwardingTargetForSelector:(SEL)selector {
    return _target;
}


- (void)forwardInvocation:(NSInvocation *)invocation
{
    void *nullPointer = NULL;
    [invocation setReturnValue:&nullPointer];
}

- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel
{
    return [NSObject instanceMethodSignatureForSelector:@selector(init)];
}

@end

PS: 要记得在dealloc调用NSTimer的invalidate方法,把定时器从run loop中移除。

你可能感兴趣的:(利用NSProxy解决NSTimer内存泄漏问题)