iOS NSTimer 循环引用

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface INWeakProxy : NSProxy

- (instancetype)initWithObjc:(id)target;

+ (instancetype)proxyWithObjc:(id)target;

@end

NS_ASSUME_NONNULL_END
#import "INWeakProxy.h"

@interface INWeakProxy ()

@property (nonatomic,weak) id target;

@end

@implementation INWeakProxy

- (instancetype)initWithObjc:(id)target {
    
    self.target = target;
    return self;
}

+ (instancetype)proxyWithObjc:(id)target {
    
    return [[self alloc] initWithObjc:target];
}



/**

 这个函数让重载方有机会抛出一个函数的签名,再由后面的forwardInvocation:去执行

 为给定消息提供参数类型信息

 */

- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel {
    
    return [self.target methodSignatureForSelector:sel];
}

/**

 * NSInvocation封装了NSMethodSignature,通过invokeWithTarget方法将消息转发给其他对象。这里转发给控制器执行。

 */

- (void)forwardInvocation:(NSInvocation *)invocation {
    
    if ([self.target respondsToSelector:invocation.selector]) {
        
        [invocation invokeWithTarget:self.target];
    }
}

使用:

INWeakProxy * proxy = [[INWeakProxy alloc] initWithObjc:self];
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:proxy selector:@selector(timeCountDown) userInfo:nil repeats:YES];

猜你喜欢