开发者

Call delegate method from a thread

开发者 https://www.devze.com 2023-02-07 14:34 出处:网络
I\'ve this bit of code: - (IBAction)registerAction:(id)sender { [NSThread detachNewThreadSelector:@selector(registerThread) toTarget:self withObject:nil];

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 _WebThr开发者_如何学GoeadLockFromAnyThread(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). Try resignFirstResponder those views before accessing delegate


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. If you were to set a breakpoint on _WebThreadLockFromAnyThread, you would know exactly where.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消