Warning: UIKit should not be called from a secondary thread

前端 未结 5 1508
悲哀的现实
悲哀的现实 2020-12-10 00:44

In my iPhone app I need to connect to a web server as this can take some time I\'m using threads like this:

[NSThread detachNewThreadSelector:@selector(sendS         


        
相关标签:
5条回答
  • 2020-12-10 00:58

    This is indeed unsafe behaviour. The MainThread is the only one that should interface the UI. Have your thread return for instance a string to the mainthread and have a method there update the UI. You can do for instance do this by passing a selector to the other thread method, and then have the other thread call the selector on the mainthread.

    0 讨论(0)
  • 2020-12-10 01:09

    It depends a little bit on what you want to do with the textField. If reading the value is the only thing, you can do:

    [NSThread detachNewThreadSelector:@selector(sendStuff) toTarget:self withObject:self.textField.text];
    
    - (void)sendStuff:(NSString*)myString {
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
        //Do someting with myString
        [pool release];
    }
    

    If you want to change a value on the textField you could:

    [self.textField performSelectorOnMainThread:@selector(setText:) withObject:@"new Text"];
    
    0 讨论(0)
  • 2020-12-10 01:11
    [self performSelectorOnMainThread:@selector(myMethod) withObject:nil waitUntilDone:NO]; 
    

    will work

    0 讨论(0)
  • 2020-12-10 01:12

    Perform any selectors that handle UI updates on the main thread. You can do this with the NSObject method -performSelectorOnMainThread:withObject:waitUntilDone:

    0 讨论(0)
  • 2020-12-10 01:20

    Why not:

    [NSThread detachNewThreadSelector: @selector(sendStuff:) toTarget: self withObject: self.textField.text];
    

    ?

    0 讨论(0)
提交回复
热议问题