KVO 底层本质:https://www.jianshu.com/p/5e3bb16e4d1b
第一、weakSelf 的宏定义写法
#define WeakObj(obj) __weak typeof(obj) o##Weak = obj;
第二、为什么子线程 runLoop 无法开启
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSLog(@"1");
[[NSRunLoop currentRunLoop]run];
[self performSelector:@selector(test) withObject:nil afterDelay:0];
NSLog(@"2");
});
}
-(void)test
{
NSLog(@"3");
}
打印结果:
2019-10-12 10:16:58.930673+0800 测试 switch[13229:1170138] 1
2019-10-12 10:16:58.930969+0800 测试 switch[13229:1170138] 2
因为run方法只是尝试想要开启当前线程中的runloop,但是如果该线程中并没有任何事件(source、timer、observer)的话,并不会成功的开启
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSLog(@"1");
[self performSelector:@selector(test) withObject:nil afterDelay:0];
[[NSRunLoop currentRunLoop]run];
NSLog(@"2");
});
}
打印结果:
2019-10-12 10:20:55.758207+0800 测试 switch[13268:1174223] 1
2019-10-12 10:20:55.758506+0800 测试 switch[13268:1174223] 3
2019-10-12 10:20:55.758620+0800 测试 switch[13268:1174223] 2
第三、performSelector: xxx onThread: xxx withObject: xxx waitUntilDone: xxx 的 waitUntilDone 的作用
它的作用是 是否阻塞当前所执行的线程
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
NSLog(@"start");
[self performSelector:@selector(helloAction) onThread:[NSThread currentThread] withObject:nil waitUntilDone:YES];
NSLog(@"end");
}
-(void)helloAction
{
NSLog(@"等待5秒");
sleep(5);
}
打印结果:
2019-10-12 15:27:56.569041+0800 测试 switch[15403:1375791] start
2019-10-12 15:27:56.569226+0800 测试 switch[15403:1375791] 等待5秒
.
.
.
2019-10-12 15:28:01.569464+0800 测试 switch[15403:1375791] end
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
NSLog(@"start");
[self performSelector:@selector(helloAction) onThread:[NSThread
currentThread] withObject:nil waitUntilDone:NO];
NSLog(@"end");
}
-(void)helloAction
{
NSLog(@"等待5秒");
sleep(5);
}
打印结果:
2019-10-12 15:32:58.978556+0800 测试 switch[15455:1380883] start
2019-10-12 15:32:58.979096+0800 测试 switch[15455:1380883] end
2019-10-12 15:32:58.979548+0800 测试 switch[15455:1380883] 等待5秒
网友评论