iOS RunLoop(2)-应用

2021-06-29  本文已影响0人  switer_iOS

RunLoop在实际开中的应用

控制线程生命周期(线程保活);
解决NSTimer在滑动时停止工作的问题;
监控应用卡顿;
性能优化;

  1. 解决NSTimer在滑动时停止工作的问题
    static int count = 0;
    // 2.添加到指定模式下
    NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
    NSLog(@"%d", ++count);
    }];
    // [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
    // [[NSRunLoop currentRunLoop] addTimer:timer forMode:UITrackingRunLoopMode];

// NSDefaultRunLoopMode、UITrackingRunLoopMode才是真正存在的模式
// NSRunLoopCommonModes并不是一个真的模式,它只是一个标记
// timer能在_commonModes数组中存放的模式下工作
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
原因:是runloop只能运行在一种模式下,timer是在默认模式下工作的,不是在UItrackRunloop的模式下工作.

  1. 线程保活
    我们先封装一个长久活命的线程

\PermanentThread.h
// 声明一个block - 用于执行任务
typedef void(^PermanentThreadTask)(void);

/** 线程保活 */
@interface PermanentThread : NSObject

// 在当前线程执行一个任务

// 结束线程

@end
\PermanentThread.m
/** CSThread **/
@interface CSThread : NSThread
@end
@implementation CSThread

@interface PermanentThread()
/** 线程/
@property(nonatomic,strong)CSThread thread;
/
是否停止*/
@property(nonatomic,assign, getter=isStopped)BOOL stopped;
@end

@implementation PermanentThread

// 初始化方法

pragma mark - public method

// 执行任务

// 停止

pragma mark - private method

// 执行任务

// 停止线程 runloop

@end

上一篇 下一篇

猜你喜欢

热点阅读