多线程:模拟时钟与运行循环
2016-03-24 14:26
204 查看
// // ViewController.m // 10-时钟与运行循环 // // Created by gzxzmac on 16/1/28. // Copyright © 2016年 gzxzmac. All rights reserved. // #import "ViewController.h" @interface ViewController () @property (nonatomic, strong) NSTimer *timer; // 定时器 @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; } - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { [self performSelectorInBackground:@selector(startTimer) withObject:nil]; } // runloop runtime - (void)startTimer { // timer 跑不准的问题: 主线程没空闲不会调用,造成中间有停顿 NSTimer *timer = [NSTimer timerWithTimeInterval:1.f target:self selector:@selector(demo) userInfo:nil repeats:YES]; self.timer = timer; // [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(demo) userInfo:nil repeats:YES]; // 使用 NSDefaultRunLoopMode 只有在主线程有空闲的时候才会调用,也就是UI优先,如果在滚动,无法调用 // NSRunLoopCommonModes 不管滚不滚动都会调用 // UITrackingRunLoopMode 滚动的时候才会调用,针对 UIScrollView [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode]; [[NSRunLoop currentRunLoop] run]; // 在当个runloop 就是哪个开始运行 // 如果想使用 CFRunLoopStop(CFRunLoopGetCurrent()); 来停止 runloop 必须使用 CFRunLoopRun() 来启动runloop // CFRunLoopRun(); } int count = 0; /* 停止 runloop 的方式 1. CFRunLoopStop(CFRunLoopGetCurrent()); 停止 CFRunLoopRun() 启动 2. 让线程里面的任务执行完成,自动停止 3. 如果是子线程的runloop 必须调用 CFRunLoopRun() 或者 [[NSRunLoop currentRunLoop] run]; 来启动 */ - (void)demo { count ++; NSLog(@"%d",count); if (count == 10) { // 注销timer [self.timer invalidate]; // CFRunLoopStop(CFRunLoopGetCurrent()); NSLog(@"end"); } } int NB; @end
相关文章推荐
- Centos6.5下安装JDK7
- 关于kernel
- MySQL5.6安装
- (java)华为机试题:字符串变换
- mysql开启慢查询方法
- MongoDB 安装与启动
- (转)性能测试之----瓶颈分析方法
- 《第一行代码:Android》读书笔记——第8章 通知和手机多媒体
- 把Flume的Source设置为 Spooling directory source
- 基于.NET平台常用的框架
- ubuntu首次安装配置
- Android App在线程中创建handler的方法讲解
- TCP/IP传送方式有三种:单播,广播,组播
- httpPost提交数据
- ViewPager加载多张图片出现内存溢出的解决办法
- 多线程:模拟循环运行
- S3C2440-GPIO和jlink配置
- 2232记录
- C++的类定义中,不能在类中定义自身类的对象,java中却可以
- SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data情况在easyui 的datagrid