美文网首页
NSProxy避免循环引用

NSProxy避免循环引用

作者: 大写的空气 | 来源:发表于2022-08-25 17:45 被阅读0次
@interface MyProxy: NSProxy
+ (instancetype)proxyWithTarget:(id)target;
@property (weak, nonatomic) id target;

@end
@implementation MyProxy

+ (instancetype)proxyWithTarget:(id)target{
      MyProxy *proxy = [MyProxy alloc];
      proxy.target = target;
      return proxy;
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel
{
    return [self.target methodSignatureForSelector:sel];
}

- (void)forwardInvocation:(NSInvocation *)invocation
{
    [invocation invokeWithTarget:self.target];
}
@end

调用

self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:[MyProxy proxyWithTarget:self] selector:@selector(timerTest) userInfo:nil repeats:YES];

MyProxy *p = [MyProxy proxyWithTarget:self] ;
[p isKindOfClass:[self class]]; //返回1,因为内部消息转发到self

相关文章

网友评论

      本文标题:NSProxy避免循环引用

      本文链接:https://www.haomeiwen.com/subject/rbkzgrtx.html