【问题标题】:Call delegate method from a thread从线程调用委托方法
【发布时间】:2011-01-28 22:43:53
【问题描述】:

我有这段代码:

- (IBAction)registerAction:(id)sender {
 [NSThread detachNewThreadSelector:@selector(registerThread) toTarget:self withObject:nil];
}

- (void)registerThread {
 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];  

 MyDelegate *delegate = (MyDelegate *)[[UIApplication sharedApplication] delegate];


 NSInteger locationID = [delegate.api checkCoordinate:[NSString stringWithFormat:@"%f,%f",
             location.coordinate.latitude, location.coordinate.longitude]];

 NSNumber *status = [api registerWithUsername:usernameField.text 
          password:passwordField.text email:emailField.text andLocation:locationID];

 [self performSelectorOnMainThread:@selector(registrationDoneWithStatus:) withObject:[NSNumber numberWithInt:1] waitUntilDone:NO];  
    [pool release];   
}

效果很好,但有时我会收到此错误:

void _WebThreadLockFromAnyThread(bool), 0x6157e30: Obtaining the web lock from a thread other than the main thread or the web thread. UIKit should not be called from a secondary thread.

而且似乎只使用委托我得到这个错误,我不知道如何解决。

提前致谢:)

【问题讨论】:

    标签: iphone objective-c ios nsthread uiapplicationdelegate


    【解决方案1】:

    我最近也遇到了同样的问题。

    可能有一些活动视图(例如UITextField,UITextView)。在访问delegate之前尝试resignFirstResponder这些视图

    【讨论】:

    • 谢谢你...这让我发疯了。在辅助线程中创建 HTTPRequest,并不断收到该错误消息。原来 UITextField 是 firstResponder。请注意,线程中没有访问这些 UI 视图!
    • 您也可以使用 [UIView endEditing:(BOOL)force] '使视图或任何作为第一响应者辞职的子视图(可选强制)'
    【解决方案2】:

    您可以通过非常仔细地考虑应用程序的并发架构并确保您没有在线程中执行任何应该只在主线程上执行的操作来解决问题。

    在这种情况下,您会导致 UIKit 从辅助线程执行代码。如果您要在 _WebThreadLockFromAnyThread 上设置断点,您就会知道确切的位置。

    在最受控制的情况下,从辅助线程使用应用程序的委托是非常不典型的。

    tl;dr 您不能通过将新线程与随机选择器分离来使应用线程化。

    【讨论】:

    • 您的意思是:“您不能通过将新线程与随机选择器分离来使应用程序线程化。”?
    • 您不能采用任何随机方法并通过detachNewThreadSelector:... 在线程中执行该方法,并希望发生正确的事情。并不是说这就是你在这里所做的——只是一般规则。线程很难。
    • mhm,如何在 _WebThreadLockFromAnyThread 上设置断点?
    • 在 Xcode 调试器中...要么通过 UI 创建一个符号断点,要么在调试器控制台中输入 'b _WebThreadLockFromAnyThread'。
    • 我试过了,但它没有触发,我不知道为什么:(但是我要更改代码,那些 api 方法正在使用 nsurlconnection sendSynchronousRequest...顺便说一句谢谢 :)
    猜你喜欢
    • 1970-01-01
    • 2011-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-26
    • 1970-01-01
    • 2012-07-20
    相关资源
    最近更新 更多