欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

iOS NSTimer 循环引用

程序员文章站 2022-07-15 10:44:08
...
#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];