简体   繁体   English

从线程调用委托方法

[英]Call delegate method from a thread

I've this bit of code: 我有这段代码:

- (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];   
}

it works nicely, but sometimes I get this error: 它工作得很好,但有时我得到这个错误:

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.

And it seems that only using the delegate I get this error, and I don't know how to resolve. 似乎只使用委托我得到这个错误,我不知道如何解决。

Thanks in advance :) 提前致谢 :)

I've run into the same problem recently. 我最近遇到了同样的问题。

There may be some active views (eg. UITextField , UITextView ). 可能存在一些活动视图(例如, UITextFieldUITextView )。 Try resignFirstResponder those views before accessing delegate 在访问delegate之前尝试resignFirstResponder这些视图

You fix the problem by very carefully thinking through your application's concurrency architecture and ensuring that you aren't exercising anything from a thread that should only be done on the main thread. 您可以通过仔细考虑应用程序的并发体系结构来确定问题并确保您不会从只应在主线程上执行的线程中执行任何操作来解决问题。

In this case, you are causing the UIKit to execute code from a secondary thread. 在这种情况下,您将使UIKit从辅助线程执行代码。 If you were to set a breakpoint on _WebThreadLockFromAnyThread, you would know exactly where. 如果你要在_WebThreadLockFromAnyThread上设置一个断点,你就会知道确切的位置。

It is exceedingly atypical to use the app's delegate from a secondary thread in anything but the most extremely controlled circumstances. 除了最严格控制的环境之外,在辅助线程中使用应用程序的委托是非常不典型的。

tl;dr You can't make an app threaded by detaching a new thread against a random selector. tl; dr您无法通过在随机选择器上分离新线程来创建应用程序线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM