1.问题:KVO监听方法可以在子线程吗?
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:
(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
NSLog(@"%@",[NSThread currentThread]);
NSLog(@"%ld",_person.age);
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[NSThread detachNewThreadWithBlock:^{
NSLog(@"%@",[NSThread currentThread]);
_person.age ++;
}];
}
打印结果:
<NSThread: 0x600003c890c0>{number = 3, name = (null)}
<NSThread: 0x600003c890c0>{number = 3, name = (null)}
总结:
将修改对象属性过程放在子线程内执行,在监听回调方法内获取当前线程同样为子线程.故KVO的响应和KVO观察的值变化是在一个线程上的.
网友评论