我有一个很奇怪的问题与异步http请求:目标C - 异步http请求块中的程序
我发送到服务器,其中以10秒的延迟,然后发送一个响应的请求。
为了不阻止程序,我做到了异步。 如果我只是调用方法(通过NSThread) - 它不起作用。我认为这是因为线程在完成之前就会死亡(服务器等待10秒)。 如果我调用方法并使用CFRunLoopRun() - 它实际上起作用,但整个程序停止工作10秒。 我的问题是如何让线程有足够的时间,并且仍然不会阻止程序运行。 当然,还有一个选项是我的代码中有一些错误导致了所有这些,所以我发布了它的所有相关部分。
这是主线程:
self.MessagesList=[[MessagesArray alloc] init];
[NSThread detachNewThreadSelector:@selector(backgroundMethod) toTarget:self withObject:nil];
-(void)backgroundMethod
{
[self.MessagesList updateFromServer];
CFRunLoopRun(); //the method dies without this line
}
,这是请求:
-(void)updateFromServer{
NSLog(@"method called");
responseData = [NSMutableData data];
NSURLRequest *request =
[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost:8000/messages/views/new_messages/"]];
NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(!connection) {
NSLog(@"connection failed :(");
} else {
NSLog(@"connection succeeded :)");
}
}
而responseData被定义为以下:
@property (nonatomic,strong) NSMutableData *responseData;
我还试图performSelectorInBackground代替的NSThread,甚至没有任何一个调用updateFromServer,并且结果也是如此同样的。
我正在与ARC合作 - 也许它与此有关?
我真的必须解决它,不知道如何,所以如果你帮我,我会很高兴。
谢谢
你为什么要使用线程?你不需要线程异步使用'NSURLConnection' – 2011-12-27 10:53:36
那么你有什么建议?我试图按照原样调用updateFromServer,但没有任何改变。也许这个请求不是异步的? – 2011-12-27 11:00:06
也许你正在做一些其他的'updateFromServer'中的阻塞 - 我不知道从这里 – 2011-12-27 11:34:39