美文网首页
iOS 解决NSTimer的循环引用问题

iOS 解决NSTimer的循环引用问题

作者: 王沐凡 | 来源:发表于2021-06-22 17:58 被阅读0次

    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];
    

    相关文章

      网友评论

          本文标题:iOS 解决NSTimer的循环引用问题

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