我的代码需要保证在主线程上运行某个操作,但调用可能来自后台线程.
为了检测后台的情况,我使用了以下内容:
- (void)selectorToRunInMainThread:(id)arguments
{
// push to main thread
if ([NSRunLoop currentRunLoop] != [NSRunLoop mainRunLoop])
{
[self performSelectorOnMainThread:@selector(selectorToRunInMainThread:) withObject:arguments waitUntilDone:NO];
return;
}
/*
... function content ...
*/
}
Run Code Online (Sandbox Code Playgroud)
这适用于iOS 4和iOS 3.2,但不适用于iOS 3.1.3及更早版本.在这些早期版本中,该函数将继续在无限循环中调用.
将比较更改为:
if (![[NSRunLoop currentRunLoop] isEqualTo:[NSRunLoop mainRunLoop]])
没有效果,他们仍然永远不会比较相同的价值.
我找到了一个似乎有效的解决方案,但我想先看看其他人的建议.
给出以下代码:
import { Keyboard } from 'react-native';
// ....
componentDidMount() {
this.keyboardShowListener = Keyboard.addListener(
'keyboardWillShow',
() => this.setState({ visible: true }),
);
this.keyboardHideListener = Keyboard.addListener(
'keyboardWillHide',
() => this.setState({ visible: false }),
);
}
// ....
onCancel() {
const { clearActiveInput } = this.props;
clearActiveInput();
Keyboard.dismiss();
}
Run Code Online (Sandbox Code Playgroud)
有没有一种正确的方法来模拟导入的Keyboard组件,以验证发生了侦听器订阅,并且还验证了dismiss()事件已触发?