【问题标题】:Warning: UIKit should not be called from a secondary thread警告:不应从辅助线程调用 UIKit
【发布时间】:2018-02-15 23:03:49
【问题描述】:

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

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

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

如何使用 textField 而不出现此错误?

【问题讨论】:

  • 为了帮助您,我们需要知道为什么要分离线程(需要这么长时间才能完成)、您需要哪些 UI 信息以及要更新哪些 UI 信息。
  • 嗨!我更新了问题。我需要连接到 Web 服务器,我需要使用 textField 中的文本发送到服务器。
  • 您应该接受 Graham Lee 或 tonklon 的回答。您应该在生成线程之前提取搜索文本并将其作为参数传递给选择器。

标签: iphone multithreading


【解决方案1】:

这在一定程度上取决于您想对 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];
}

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

[self.textField performSelectorOnMainThread:@selector(setText:) withObject:@"new Text"];

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      为什么不:

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

      ?

      【讨论】:

        【解决方案4】:

        这确实是不安全的行为。 MainThread 是唯一应该与 UI 交互的线程。例如,让您的线程将一个字符串返回到主线程,并在那里有一个方法更新 UI。例如,您可以通过将选择器传递给另一个线程方法来做到这一点,然后让另一个线程调用主线程上的选择器。

        【讨论】:

          【解决方案5】:
          [self performSelectorOnMainThread:@selector(myMethod) withObject:nil waitUntilDone:NO]; 
          

          会起作用

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-06-14
            • 2011-12-11
            • 1970-01-01
            • 2022-01-05
            • 2011-05-22
            相关资源
            最近更新 更多