//
// 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