RunLoop入门

 

runloop在主线程里面是默认开启的,在子线程里是默认关闭的。

 

一、简介

首先,先象征性的讲下RunLoop的概念
从字面上看,就可以看出就是兜圈圈,就是一个死循环嘛。

二、作用

1.保持程序运行
2.处理app的各种事件(比如触摸,定时器等等)
3.节省CPU资源,提高性能。

2.RunLoop与线程

1.每条线程都有唯一的与之对应的RunLoop对象。
2.主线程的RunLoop已经创建好了,而子线程的需要手动创建。(也就是说子线程的RunLoop默认是关闭的,因为有时候开了个线程但却没有必要开一个RunLoop,不然反而浪费了资源。 )
3.RunLoop在第一次获取时创建,在线程结束时销毁。(这就相当于 线程是一个类,RunLoop是类里的实例变量,这样便于理解)

 

例子NSTimer的使用

在项目中用的NSTimer其实也和RunLoop有关系,下面我们来做个实验

实验一 scheduledTimer方法

修改一下button的响应以及timerTest方法,代码如下

- (IBAction)ButtonDidClick:(id)sender{

[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerTest) userInfo:nil repeats:YES];

}

- (void)timerTest {

NSLog(@"timerTest----");

}

点击button可以看到输出台每隔一秒钟就打印"timerTest----"。
 

 

实验二 timerWithTime方法

代码如下

- (IBAction)ButtonDidClick:(id)sender { NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(timerTest) userInfo:nil repeats:YES]; } - (void)timerTest { NSLog(@"timerTest----"); }
但是实验结果是,点击button后没有反应。为什么呢?
噢~原来是少加了一句话,添加后的代码如下:

- (IBAction)ButtonDidClick:(id)sender { NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(timerTest) userInfo:nil repeats:YES]; [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode]; } - (void)timerTest { NSLog(@"timerTest----"); }

可是,为什么实验二比实验一要多加一句话呢?解:那是因为scheduledTimer方法会自动添加到当前的runloop里面去,而且runloop的运行模式kCFRunLoopDefaultMode,也就是说实验一已经将timer自动加入到了一个运行模式为kCFRunLoopDefaultMode的runloop中。

 

 

实验三 有scrollView的情况下使用Timer

首先,按钮响应以及timerTest的方法如下:

- (IBAction)ButtonDidClick:(id)sender { NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(timerTest) userInfo:nil repeats:YES]; [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode]; } - (void)timerTest { NSLog(@"timerTest----"); }



 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值