一,使用NSProxy
先看官网介绍:
An abstract superclass defining an API for objects that act as stand-ins for other objects or for objects that don’t exist yet.
这是一个超类,可以作为其他对象的替身
二,官网实现
我们需要实现俩个方法
- (void)forwardInvocation:(NSInvocation *)invocation;
- (nullable NSMethodSignature *)methodSignatureForSelector:(SEL)sel NS_SWIFT_UNAVAILABLE("NSInvocation and related APIs not available");
二,实现自己的类
#import "MyProxy.h"
@interface MyProxy ()
@property (nullable, nonatomic, weak, readonly) id target;
@end @implementation MyProxy
+ (id)proxyWithTarget:(id)target{
MyProxy * proxy = [MyProxy alloc];
proxy->_target = target; return proxy; }
//重写以下俩个方法
- (void)forwardInvocation:(NSInvocation *)invocation{
if ([_target respondsToSelector:invocation.selector]) {
// NSLog(@"Before calling \"%@\".", NSStringFromSelector(invocation.selector)); [invocation invokeWithTarget:_target];
// NSLog(@"After calling \"%@\".", NSStringFromSelector(invocation.selector));
}
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel{
return [_target methodSignatureForSelector:sel]; }
@end
三,使用使用myproxy代理你的对象就可以实现打破循环引用,防止内存泄漏
self.timer = [NSTimer scheduledTimerWithTimeInterval:0.5
target:[MyProxy proxyWithTarget:self]
selector:@selector(test)
userInfo:nil
repeats:YES];
四,除了重写上边俩个方法,也可以重写runtime消息转发方法。
// 也可以单独实现这一个方法;
- (id)forwardingTargetForSelector:(SEL)aSelector{return _target;}