UI高级--------NSRunLoop

本文介绍了NSRunLoop的概念及其如何维持线程活动状态,探讨了定时器的不同使用方式,包括在不同线程中的应用,并对比了NSTimer与CADisplayLink在实现精准定时任务方面的差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.NSRunLoop的基本概念

  • Run Loop 是线程相关的的基础框架的一部分。一个 run loop 就是一个事件处理 的循环,用来不停的调度工作以及处理输入事件。
  • 线程的生命周期存在五个状态:新建、就绪、运行、阻塞、死亡
  • NSRunLoop可以保持一个线程一直为活动状态,不会马上销毁掉。

二.定时器的普通使用与在线程中的使用

#import "ViewController.h"

@interface ViewController ()
{
    int index;
    int indexCount;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    index = 60;

    //1 此方法是默认添加到当前的runloop中的
//    [NSTimer scheduledTimerWithTimeInterval:.2 target:self selector:@selector(repeatAction) userInfo:nil repeats:YES];

    //2
    /*
    //(1)创建定时器
    NSTimer *timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(repeatAction) userInfo:nil repeats:YES];
    //(2)把定时器对象添加到当前的runLoop中
    [[NSRunLoop currentRunLoop]addTimer:timer forMode:NSDefaultRunLoopMode];
    //(3)开启定时器
    [timer fire];
    */

    //3 后台线程调用定时器
//    [self performSelectorInBackground:@selector(backgroundTimer) withObject:nil];

    //NStimer实现的定时器不是很准确,会受到当前线程中其他操作的影响
//    long long j =0;
//    for (long i =0; i<1000000000; i++) {
//        j+=i;
//    }


    //屏幕刷新率 60HZ

    //实现一个精确的定时器 (1/60s调用一次)
    CADisplayLink *link = [CADisplayLink displayLinkWithTarget:self selector:@selector(repeatAction)];
    [link addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

    //CADisplayLink 不受其他线程的影响
        long long j =0;
        for (long i =0; i<1000000000; i++) {
            j+=i;
        } 
}
-(void)repeatAction{

    indexCount++;
    if (indexCount == 60) {
        index--;
        NSLog(@"index = %d",index)
        indexCount= 0;  
    }
}

//后台线程调用的方法
-(void)backgroundTimer{
    /*
     (1) 主线程中的runloop默认是启动的,用于接收各种输入source
     (2) 对于第二线程来说,runloop默认是没有启动的.

     */


    //(1)创建timer (2)添加到当前的runloop  (3)fire
    [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(repeatAction) userInfo:nil repeats:YES];

    //让当前runloop一直运行
    //保证当前的线程不被销毁掉
    [[NSRunLoop currentRunLoop] run];
    //等效于:
//    [[NSRunLoop currentRunLoop] runUntilDate:[NSDate distantFuture]]; 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值