iOS 关于定时器NSTimer

    技术2022-07-13  84

    一、默认就会执行 ,是在 NSDefaultRunLoopMode 模式下运行的 。如果滑动会切换 UITrackingRunLoopMode  定时器失效。

    [NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) { NSLog(@"currentMode == %@",[NSRunLoop currentRunLoop].currentMode); }];

    二、默认不会执行 ,需要添加到 当前RunLoop  可以指定具体的运行模式.NSRunLoopCommonModes 不是真正的模式,是占位模式(NSDefaultRunLoopMode、UITrackingRunLoopMode)都会执行。

    NSTimer * timer = [NSTimer timerWithTimeInterval:2 repeats:YES block:^(NSTimer * _Nonnull timer) { NSLog(@"currentMode= %@",[NSRunLoop currentRunLoop].currentMode); }]; [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

    NSTimer 会对target 产生强引用,如果target又对它们产生强引用,那么就会引发循环引用

    1、使用block

    -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { //Block; __weak typeof(self) weakSelf = self; self.timer = [NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) { [weakSelf clickTest]; }]; } -(void)clickTest{ NSLog(@"%@",[NSThread currentThread]); } - (void)dealloc { [self.timer invalidate]; NSLog(@"%s",__func__); }

    2、target: 使用代理对象   :target 必须为弱指针

    方式一、继承NSObject

    // YMProxy 类 @interface YMProxy : NSObject +(instancetype)proxyWith:(id)target; //弱指针 @property (nonatomic,weak) id target; @end @implementation YMProxy +(instancetype)proxyWith:(id)target{ YMProxy * proxy = [[YMProxy alloc]init]; proxy.target = target; return proxy; } //消息转发 -(id)forwardingTargetForSelector:(SEL)aSelector { return self.target; } @end //使用 -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:[JMProxy proxyWith:self] selector:@selector(clickTest) userInfo:nil repeats:YES]; } -(void)clickTest{ NSLog(@"%@",[NSThread currentThread]); } - (void)dealloc { [self.timer invalidate]; NSLog(@"%s",__func__); }

    方式二、继承NSProxy

    //JMProxy @interface JMProxy : NSProxy +(instancetype)proxyWith:(id)target; //弱指针 @property (nonatomic,weak) id target; @end @implementation JMProxy +(instancetype)proxyWith:(id)target { JMProxy * proxy = [JMProxy alloc]; proxy.target = target; return proxy; } - (NSMethodSignature *)methodSignatureForSelector:(SEL)sel { return [self.target methodSignatureForSelector:sel]; } -(void)forwardInvocation:(NSInvocation *)invocation { [invocation invokeWithTarget:self.target]; } //使用 -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:[JMProxy proxyWith:self] selector:@selector(clickTest) userInfo:nil repeats:YES]; } -(void)clickTest{ NSLog(@"%@",[NSThread currentThread]); } - (void)dealloc { [self.timer invalidate]; NSLog(@"%s",__func__); }

     

    Processed: 0.015, SQL: 9