weakProxy打破循环引用,防止内存泄漏

Demo地址

一,使用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;}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容