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

//
//  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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值