iOS 13以后可以通过block解决target的强引用问题,如果程序兼顾iOS13以下,那么使用NSProxy是最好的解决办法:
@interface timerProxy : NSProxy
//通过创建对象
- (instancetype)initWithObjc:(id)object;
//通过类方法创建创建
+ (instancetype)proxyWithObjc:(id)object;
@end
@interface timerProxy ()
@property (nonatomic, weak) id object;
@end
@implementation timerProxy
- (instancetype)initWithObjc:(id)object {
self.object = object;
return self;
}
+ (instancetype)proxyWithObjc:(id)object {
return [[self alloc] initWithObjc:object];
}
- (void)forwardInvocation:(NSInvocation *)invocation {
if ([self.object respondsToSelector:invocation.selector]) {
[invocation invokeWithTarget:self.object];
}
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel {
return [self.object methodSignatureForSelector:sel];
}
@end
使用的时候:
timerProxy* proxy = [timerProxy proxyWithObjc:self];
self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:proxy selector:@selector(timerAction) userInfo:nil repeats:YES];