从线程调用委托方法

时间:2011-01-28 22:43:53

标签: iphone objective-c ios nsthread uiapplicationdelegate

我有这段代码:

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

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

提前致谢:)

2 个答案:

答案 0 :(得分:3)

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

可能会有一些有效观点(例如UITextFieldUITextView)。在访问resignFirstResponder

之前,请尝试delegate这些观看

答案 1 :(得分:1)

您可以通过仔细考虑应用程序的并发体系结构来确定问题,并确保您不会从只应在主线程上执行的线程中执行任何操作。

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

除了最严格控制的情况外,在辅助线程中使用应用程序的委托是非常不典型的。

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

相关问题