performSelectorInBackground可以访问UI

时间:2014-09-15 14:44:17

标签: ios multithreading

我有一个iOS应用程序。它检查主线程中的网络连接。有时,它会阻塞。所以我分出了一个子线程来在新代码中进行网络检查。有趣的是,子线程能够弹出警报窗口。我以为所有UI都只由主线程控制。有什么想法吗?

旧代码:

Reachability *m_checkReachability=[Reachability reachabilityWithHostName:@"www.xxx.edu"]; 

新代码:

[self performSelectorInBackground:@selector(checkConnectivity) withObject:nil]; 

(void)checkConnectivity{ 
    Reachability *m_checkReachability=[Reachability  reachabilityWithHostName:@"www.xxx.edu"]; 

if (![m_checkReachability isReachable]) 
{
    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Error" message:@"Network is not availabe. Do you want to close the app?" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; 

    [alert show]; 
}

我知道performSelectorInBackground是一种古老的方式。试着理解为什么它仍然拥有对UI的控制权,这应该属于主线程?

1 个答案:

答案 0 :(得分:0)

这只是可能导致问题的糟糕代码。编译器不知道代码可以从后台线程进行UI调用,因此它很乐意编译代码。解决方案是在主线程上调用UI。