IOS学习 多线程NSThread 消息循环(了解)涉及定时器

#import "ViewController.h"


@interface ViewController ()

{

    BOOL shouldKeepRunning;

}

@end


@implementation ViewController


- (void)viewDidLoad {

    [superviewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    UITextView *textView = [[UITextViewalloc]initWithFrame:CGRectMake(0,20, 300,150)];

    textView.text =@"“北京房地产中介下架了近万套高价房源。昨日,一位地产人士表示,这在业内已经不是一个秘密。日前,市住建委开展了对房地产中介专项执法检查,包括擅自发布房源信息、哄抬房价等不良行为。此前,北京各家房地产中介纷纷下架了高价房源,北京甚至出现大批学区房一夜之间价格统一跌到14.99万元的现象。";

    textView.font = [UIFontsystemFontOfSize:20];

    [self.viewaddSubview:textView];

    

    shouldKeepRunning =NO;

}


-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    [selfdemo2];

}


//主线程消息循环,默认开启

- (void)demo{

    //创建timer 参数4:自定义    参数5:是否重复执行

    NSTimer *timer = [NSTimertimerWithTimeInterval:2target:selfselector:@selector(task)userInfo:nilrepeats:YES];


    //把定时器加入当前线程的消息循环中 参数1:定时源  参数2:模式

    /*现象:

     *NSDefaultRunLoopMode:拖动界面,定时源不运行

     *NSRunLoopCommonModes:拖动界面,正常运行,没有影响

        没有拖动界面:kCFRunLoopDefaultMode

        拖动界面:UITrackingRunLoopMode

     */

    

    [[NSRunLoopcurrentRunLoop] addTimer:timerforMode:NSRunLoopCommonModes];

}


- (void)task{

    //输出当前循环模式

    NSLog(@"%@",[NSRunLoopcurrentRunLoop].currentMode);

    NSLog(@"task is running");

}


//子线程消息循环,默认关闭

- (void)demo2{

    NSThread *thread = [[NSThreadalloc]initWithTarget:selfselector:@selector(task2)object:nil];

    [thread start];

    /*

    //在指定线程中的消息循环中加入源

    //参数1:方法/参数2:指定线程/参数3:对象/参数4:等待方法执行完成

    [self performSelector:@selector(addtask) onThread:thread withObject:nil waitUntilDone:NO];

    //开启消息循环 使用run方法,无法停止

    [[NSRunLoop currentRunLoop]run];

    

    //第二种:指定循环运行时间

    [[NSRunLoop currentRunLoop]runUntilDate:[NSDate dateWithTimeIntervalSinceNow:2]];

    */

    //第三种:apple推荐的方法 (了解)

//    BOOL shouldKeepRunning = YES;        // global

    NSRunLoop *theRL = [NSRunLoopcurrentRunLoop];

    while (shouldKeepRunning && [theRLrunMode:NSDefaultRunLoopModebeforeDate:[NSDatedistantFuture]]);

    

    NSLog(@"over");

}


-(void)task2{

    //输出当前循环模式

//    NSLog(@"%@",[NSRunLoop currentRunLoop].currentMode);

    NSLog(@"task is running:%@",[NSThreadcurrentThread]);

}


-(void)addtask{

    NSLog(@"addtask is running");

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值