[英]Call delegate method from a thread
我有这段代码:
- (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.
似乎只使用委托我得到这个错误,我不知道如何解决。
提前致谢 :)
我最近遇到了同样的问题。
可能存在一些活动视图(例如, UITextField
, UITextView
)。 在访问delegate
之前尝试resignFirstResponder
这些视图
您可以通过仔细考虑应用程序的并发体系结构来确定问题并确保您不会从只应在主线程上执行的线程中执行任何操作来解决问题。
在这种情况下,您将使UIKit从辅助线程执行代码。 如果你要在_WebThreadLockFromAnyThread上设置一个断点,你就会知道确切的位置。
除了最严格控制的环境之外,在辅助线程中使用应用程序的委托是非常不典型的。
tl; dr您无法通过在随机选择器上分离新线程来创建应用程序线程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.