您的位置:首页 > 其它

多线程:模拟时钟与运行循环

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: