NSProxy定时器
2019-10-24 本文已影响0人
大冯宇宙
NSProxy是一个专门用来消息转发的抽象类,发送给Proxy的消息会被转发给实际对象,或使Proxy加载(转化为)实际对象。NSProxy与NSObject同级别,没有父类。这里我们使用NSProxy写一个定时器,可以解决定时器的内存泄露问题。
.h
@interface XGProxy : NSProxy
@property (nonatomic, weak) id target;
+ (instancetype)proxyWithTarget:(id)target;
@end
.m
@implementation XGProxy
+ (instancetype)proxyWithTarget:(id)target {
XGProxy * proxy = [XGProxy alloc];
proxy.target = target;
return proxy;
}
// 调用时候就会返回方法签名
- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel {
return [self.target methodSignatureForSelector:sel];
}
// 进行消息转发
- (void)forwardInvocation:(NSInvocation *)invocation {
[invocation invokeWithTarget:self.target];
}
@end
使用:
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:[XGProxy proxyWithTarget:self] selector:@selector(timerS) userInfo:nil repeats:YES];
}
- (void)timerS {
}
- (void)dealloc {
[self.timer invalidate];
}
@end