警告:不应从辅助线程调用UIKit

Mar*_*tin 2 iphone multithreading

在我的iPhone应用程序中,我需要连接到Web服务器,因为这可能需要一些时间我使用这样的线程:

[NSThread detachNewThreadSelector:@selector(sendStuff) toTarget:self withObject:nil];

- (void)sendStuff {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    //Need to get the string from the textField to send to server
    NSString *myString = self.textField.text;

    //Do some stuff here, connect to web server etc..

    [pool release];
}
Run Code Online (Sandbox Code Playgroud)

在我使用self.textField的行上,我在控制台中收到一条警告:void _WebThreadLockFromAnyThread(bool),0x5d306b0:从主线程或Web线程以外的线程获取Web锁定.不应该从辅助线程调用UIKit.

如何在不收到此错误的情况下使用textField?

ton*_*lon 12

这取决于你想用textField做什么.如果只读取值,您可以:

[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];
}
Run Code Online (Sandbox Code Playgroud)

如果要更改textField上的值,您可以:

[self.textField performSelectorOnMainThread:@selector(setText:) withObject:@"new Text"];
Run Code Online (Sandbox Code Playgroud)


Ale*_*lds 11

执行在主线程上处理UI更新的任何选择器.您可以使用NSObject方法执行此操作-performSelectorOnMainThread:withObject:waitUntilDone: