【问题标题】:Calling a function through thread giving an exception通过线程调用函数给出异常
【发布时间】:2013-04-17 06:42:55
【问题描述】:

我正在使用线程调用我的函数“initialGetMethod”

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

我的get方法是

-(void) initialGetMethod
{
    self.loginPassword = [[ UIAlertView alloc] initWithTitle:@"Please Login to MFP" message:@"Enter Valid UserID and Password" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:@"Cancel", nil];
    [self.loginPassword setAlertViewStyle:UIAlertViewStyleLoginAndPasswordInput];
    [self.loginPassword setTag:2];
    [self.loginPassword show];
}

但它给出了异常“试图从主线程或网络线程以外的线程获取网络锁。这可能是从辅助线程调用 UIKit 的结果。”

它在“[self.loginPassword setAlertViewStyle:UIAlertViewStyleLoginAndPasswordInput];”处给出异常

如果我将该函数称为“[self initialGetMethod];”它没有给出例外,但需要一些时间..

我尝试在后台加载,但它不工作..(意味着我不希望它在后台)..

请提出一些解决方案..

【问题讨论】:

  • 您无法在后台线程上执行 UI 操作,您为什么要这样做?
  • 为什么用 iPhone-sdk-4.0 标记?我希望您不要尝试支持 iOS 4.0。
  • 我尝试使用“[NSThread detachNewThreadSelector:@selector(initialGetMethod) toTarget:self withObject:nil];”但仍然得到同样的例外..
  • 不...我使用的是 iOS 4.3..

标签: ios objective-c nsthread


【解决方案1】:

您在运行应用程序时遇到的错误是

"试图从主线程或web线程以外的线程获取web lock。这可能是从辅助线程调用UIKit的结果。"

当您在除 MainThread 之外的任何其他线程中更新或访问 UI 元素时会发生这种情况(仅使用 Main 线程来访问或更新 UI,它只会帮助您)

这里你在后台线程中显示警报,这就是它发生的原因

请使用以下之一来弹出警报

  [self performSelector:@selector(initialGetMethod) withObject:nil];

  [self performSelector:@selector(initialGetMethod) withObject:nil afterDelay:0.1];

【讨论】:

    【解决方案2】:
     //call createthread:
    
        [self setupTimerThread:];
    
    
    
           //write following code in setupTimerThread
           timer = [NSTimer timerWithTimeInterval:02
                                            target:self
                                          selector:@selector(initialGetMethod:)
                                          userInfo:nil
                                           repeats:NO];
           NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
           [runLoop addTimer:timer forMode:NSRunLoopCommonModes];
           [runLoop run];
    

    【讨论】:

    • 试试我编辑的答案。如果问题是由于后台 UI 更新引起的,它应该可以工作。
    • 试试我编辑的答案。如果只有运行循环发生变化,保持线程不变,它可能会起作用。
    • 您不能在后台线程上运行 UI 操作,只能在主线程上执行 UI 操作。这就是为什么您的代码不起作用的原因,您正在创建一个新线程并尝试在其上运行 UI 操作。这是不正确的。
    猜你喜欢
    • 1970-01-01
    • 2013-04-29
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多