委托方法

委托方法

问题描述:

我有这段代码:委托方法

- (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. 

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

感谢提前:)

,您可以通过应用程序的并行架构非常仔细地思考,并确保你不是从只应在主线程中完成一个线程行使任何解决问题。

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

这是非常非典型的使用应用程序的代理从辅助线程中的任何东西,但最极端的控制环境。

tl; dr您无法通过将新线程与随机选择器分离来创建应用程序。

+0

你是什么意思:“你不能通过将一个新线程与一个随机选择器分开来使应用线程化。”? – patrick 2011-01-28 23:20:15

+0

您不能采用任何随机方法,并通过`detachNewThreadSelector:`在线程中执行该方法,并且希望发生正确的事情。不是说这就是你在这里做的 - 只是一个普遍的规则。线程很难。 – bbum 2011-01-29 00:26:41

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

可能存在一些活动视图(例如,UITextFieldUITextView)。尝试resignFirstResponder访问之前的那些意见delegate