您好,欢迎来到二三娱乐。
搜索
您的当前位置:首页weakProxy打破循环引用,防止内存泄漏

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

来源:二三娱乐

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

Copyright © 2019- yule263.com 版权所有 湘ICP备2023023988号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务