iOS - Runloop在实际开发中的应用

iOS - Runloop在实际开发中的应用

1. 控制线程生命周期(线程保活)

如果需要经常在子程序执行任务,可能希望一个线程可以重复使用,避免每次都要创建、销毁带来不必要的开销

ZSXPermenantThread.h

objectivec 复制代码
typedef void (^ZSXPermenantThreadTask)(void);

@interface ZSXPermenantThread : NSObject

/**
 开启线程
 */
//- (void)run;

/**
 在当前子线程执行一个任务
 */
- (void)executeTask:(ZSXPermenantThreadTask)task;

/**
 结束线程
 */
- (void)stop;

@end

ZSXPermenantThread.m

objectivec 复制代码
#import "ZSXPermenantThread.h"

/** ZSXThread **/
@interface ZSXThread : NSThread
@end
@implementation ZSXThread
- (void)dealloc
{
    NSLog(@"%s", __func__);
}
@end

/** ZSXPermenantThread **/
@interface ZSXPermenantThread()

@property (strong, nonatomic) ZSXThread *innerThread;
@property (assign, nonatomic, getter=isStopped) BOOL stopped;

@end

@implementation ZSXPermenantThread

#pragma mark - public methods
- (instancetype)init {
    if (self = [super init]) {
        self.stopped = NO;
        
        __weak typeof(self) weakSelf = self;
        
        self.innerThread = [[ZSXThread alloc] initWithBlock:^{
            [[NSRunLoop currentRunLoop] addPort:[[NSPort alloc] init] forMode:NSDefaultRunLoopMode];
            
            while (weakSelf && !weakSelf.isStopped) {
                [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
            }
        }];
        
        [self.innerThread start];
    }
    return self;
}

- (void)executeTask:(ZSXPermenantThreadTask)task {
    if (!self.innerThread || !task) return;
    
    [self performSelector:@selector(__executeTask:) onThread:self.innerThread withObject:task waitUntilDone:NO];
}

- (void)stop {
    if (!self.innerThread) return;
    
    [self performSelector:@selector(__stop) onThread:self.innerThread withObject:nil waitUntilDone:YES];
}

- (void)dealloc {
    NSLog(@"%s", __func__);
    
    [self stop];
}

#pragma mark - private methods
- (void)__stop {
    self.stopped = YES;
    CFRunLoopStop(CFRunLoopGetCurrent());
    self.innerThread = nil;
}

- (void)__executeTask:(ZSXPermenantThreadTask)task {
    task();
}

@end

在 ViewController中使用

less 复制代码
@interface ViewController ()

@property (strong, nonatomic) ZSXPermenantThread *thread;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.thread = [[ZSXPermenantThread alloc] init];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.thread executeTask:^{        NSLog(@"执行任务 - %@", [NSThread currentThread]);
    }];
}


- (IBAction)stop:(UIButton *)sender {
    [self.thread stop];
}


- (void)dealloc
{
    NSLog(@"%s", __func__);
}

@end

运行结果:

2. 解决NSTimer在滑动时停止工作的问题

2.1. 案例

使用NSTimer创建一个定时器,循环打印

objectivec 复制代码
[NSTimer scheduledTimerWithTimeInterval:1.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
    NSLog(@"%d", ++count);
}];

当scrollView 滚动时,定时器就停止了

2.2 解决

objectivec 复制代码
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 并不是一个真的模式,它只是一个标记而已
// time 能在_commonModes数组中存放的的模式下工作。也就是包含NSDefaultRunLoopMode、UITrackingRunLoopMode
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

3. 监控应用卡顿

4. 性能优化

@oubijiexi

相关推荐
QQ_43766431412 分钟前
Linux下可执行程序的生成和运行详解(编译链接汇编图解)
linux·运维·c语言·汇编·caffe
窦再兴1 小时前
来一个复古的技术FTP
linux·运维·服务器
xiaobin889991 小时前
【2025最新版】VMware虚拟机下载安装教程 保姆级图文详解(附安装包+常用镜像Linux,win11,ubuntu,centos)
linux·其他·ubuntu·centos
ALex_zry2 小时前
Ubuntu 20.04 C++开发环境搭建指南(2025版)
linux·c++·ubuntu
疯狂的挖掘机2 小时前
记一次从windows连接远程Linux系统来控制设备采集数据方法
linux·运维·windows
sz66cm3 小时前
Linux基础 -- 用户态Generic Netlink库高性能接收与回调框架
linux
数巨小码人3 小时前
Linux常见命令
大数据·linux·运维·服务器·elasticsearch·搜索引擎
邪恶的贝利亚4 小时前
定时器设计
java·linux·前端
magic 2454 小时前
第五章:Linux用户管理
linux·运维·服务器
前进的程序员4 小时前
C++ 在 Windows 和 Linux 平台上的开发差异及常见问题
linux·c++·windows