iOS runLoop 用法详解3


//
//  ViewController.m
//  test_runLoop_01
//
//  Created by jeffasd on 16/7/25.
//  Copyright © 2016年 jeffasd. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
{
    BOOL _isPlaying;
}

//@property (nonatomic, assign) BOOL isPlaying;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _isPlaying = NO;
    
    [NSThread detachNewThreadSelector:@selector(doSomething) toTarget:self withObject:nil];
    

    // 并不会让 for循环执行时去执行 touch事件
    for (int i = 0; i < 1000 * 100; i++) {
        
        NSLog(@"for for");
        //        [[NSRunLoop currentRunLoop] runUntilDate:[NSDate distantPast]];
        //        [[NSRunLoop currentRunLoop] runUntilDate: [NSDate distantPast]];
                [[NSRunLoop mainRunLoop] runMode:NSRunLoopCommonModes beforeDate:[NSDate distantFuture]];
//        [[NSRunLoop mainRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
        
    }
    
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    self.view.backgroundColor = [UIColor redColor];
    
    
    while (_isPlaying == NO) {
        NSLog(@"runloop while");
//        [[NSRunLoop currentRunLoop] runUntilDate:[NSDate distantPast]];
        //注意将runloot 运行在NSDefaultRunLoopMode时由于此时间优先级较低,所以可能导致 complete 执行时间 不是5秒后
//        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
        
        //使用commonModes 能保证 complete在5秒后执行
        [[NSRunLoop currentRunLoop] runMode:NSRunLoopCommonModes beforeDate:[NSDate distantFuture]];
    }
    
    NSLog(@"runLoop complete");
    
}

- (void)doSomething{
    
    for (int i = 0; i < 1000 * 100; i++) {
        
        NSLog(@"for for");
        //        [[NSRunLoop currentRunLoop] runUntilDate:[NSDate distantPast]];
        //        [[NSRunLoop currentRunLoop] runUntilDate: [NSDate distantPast]];
        
//        [[NSRunLoop currentRunLoop] runMode:NSRunLoopCommonModes beforeDate:[NSDate distantFuture]];
        
    }
    
    sleep(5);
    //在子线程修改此值
//    _isPlaying = YES;
    
    //局部 基本类型的值 必须加 __block 关键字修饰
    __block BOOL over = NO;
    
    dispatch_sync(dispatch_get_main_queue(), ^{
        
        //此写法实际是下面的写法 是对self内的变量值得修改其会对self做一次retain
        _isPlaying = YES;
        self->_isPlaying = YES;
        
        over = YES;
        
        
    });
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值