我有UITextField的子类MyTextField。它是它自己的委托,但是具有myDelegate变量(由调用方设置),因此我可以将这两个委托消息传递回调用方:
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
if ( [myDelegate respondsToSelector:@selector(textFieldDidBeginEditing:)] ) {
int isMainThread = [NSThread isMainThread];
NSLog(@"isMainThread %d",isMainThread); // isMainThread 1
// case 1: this does not work (myDelegate never executes textFieldDidBeginEditing:)
[myDelegate performSelector:@selector(textFieldDidBeginEditing:) withObject:textField afterDelay:0];
// case 2: but this works: Why?
[myDelegate performSelectorOnMainThread:@selector(textFieldDidBeginEditing:) withObject:textField waitUntilDone:NO];
}
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
if ( [myDelegate respondsToSelector:@selector(textFieldDidEndEditing:)] ) {
// case 3: this always works
[myDelegate performSelector:@selector(textFieldDidEndEditing:) withObject:textField afterDelay:0];
}
}
为什么在情况1(而不是情况3)的情况下,为什么我必须使用performSelectorOnMainThread:尽管代码始终始终在主线程上?
(我想是在某个地方有一个cancelPreviousPerformRequestsWithTarget:,但不是我自己的。)
编辑1:在第3种情况下,我也必须使用performSelectorOnMainThread:。
编辑2:为什么不这样做
[myDelegate textFieldDidBeginEditing:textField];
而不是performSelector:?