runLoop运行模式示例代码

本文介绍了一个关于RunLoop和定时器的示例代码,演示了如何在主线程和子线程中使用定时器,并自动将其添加到RunLoop的默认模式中。此外,还展示了如何手动控制子线程的RunLoop。

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

runLoop运行模式示例代码

通过 timer2 这种方式创建定时器,不再需要手动添加到runloop里面,该方法内部会自动添加,并且设置运行模式为默认模式。

要注意的是 子线程的runloop是需要自己创建的

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
//    [self timer2];
    [NSThread detachNewThreadSelector:@selector(timer2) toTarget:self withObject:nil];
}


-(void)timer
{
    //创建定时器
   NSTimer *timer= [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(run) userInfo:nil repeats:NO];
    
    //添加定时器到RunLoop中
    //参数1:定时器   参数2: runloop的运行模式
    [[NSRunLoop currentRunLoop]addTimer:timer forMode:NSDefaultRunLoopMode];
}


-(void)timer2
{
    NSRunLoop *runloop=[NSRunLoop currentRunLoop];
    [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(run) userInfo:nil repeats:NO];
    [runloop run];
}
-(void)run
{
    NSLog(@"------%@-------%@",[NSThread currentThread],[NSRunLoop currentRunLoop].currentMode);
}

@end




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值