在iOS開發(fā)中經(jīng)常使用到NSTimer恋追,我們都知道NSTimer會對target retain一次冬殃,導(dǎo)致相互強引用target無法釋放。我們可以消息轉(zhuǎn)發(fā)代理NSProxy來解決NSTimer內(nèi)存泄漏問題粱甫。
具體代碼如下:
#import <Foundation/Foundation.h>
@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調(diào)用NSTimer的invalidate方法搂漠,把定時器從run loop中移除。