Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/iphone/41.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Iphone Objective-C中的多线程_Iphone_Objective C_Multithreading - Fatal编程技术网

Iphone Objective-C中的多线程

Iphone Objective-C中的多线程,iphone,objective-c,multithreading,Iphone,Objective C,Multithreading,我试图在后台运行一个方法,但它仍然会阻塞程序。 这是我的代码: - (void)viewDidLoad { [super viewDidLoad]; self.MessagesList=[[MessagesArray alloc] init]; [self performSelectorInBackground:@selector(backgroundMethod) withObject:nil]; } -(v

我试图在后台运行一个方法,但它仍然会阻塞程序。 这是我的代码:

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        self.MessagesList=[[MessagesArray alloc] init];

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


    -(void)backgroundMethod
    {
        if ([MessagesList updateFromServer]){
            [self.Table reloadData];
             CFRunLoopRun();
    }
}
updateFromServer向服务器发送HTTP请求并等待响应时,服务器会将响应延迟10秒,结果整个程序也会延迟10秒。你能纠正我吗

更新:我添加了一个runloop行,但问题仍然是一样的。HTTP请求是异步的,但仍然是-整个程序等待服务器响应。这是我的updateFromServer方法:

responseData = [NSMutableData data];
[self setBaseURL:[NSURL URLWithString:@"http://localhost:8000/messages/views/new_messages/"]];
NSURLRequest *request =
    [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost:8000/messages/views/new_messages/"]];
NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
return TRUE;

如何使其真正异步?

始终在主线程上更新UI,
[self.Table reloadData]
不会在后台线程上更新。您如何发送HTTP请求?NSURLConnection是异步连接还是同步连接


如果它是一个同步连接,那么它会阻止正在运行的线程,直到收到响应。

当我运行同步请求时,它会阻止它。异步只是不运行(如果我从主线程调用它,它就会运行,但是if语句会阻塞,因为它正在等待响应)。任何方式-如果我需要始终检查来自服务器的更新,如何从主线程更新UI?从后台线程,您可以在任何NSObject上调用-[NSObject performSelectorOnMainThread:withObject:waitUntilDone:]。我在很多地方都这样做了,效果非常好。@AmitHagin,为你的后台线程异步NSURLConnection添加一个运行循环。这没有帮助。出于某种原因,它的工作方式类似于同步请求。我添加了更多的代码。。。你能找到问题吗?改用NSThread怎么样?我也试过了。没有什么变化。谢谢