【发布时间】:2011-12-27 10:07:45
【问题描述】:
我遇到了一个非常奇怪的异步 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 -
那你有什么建议?我尝试按原样调用 updateFromServer,但没有任何改变。也许请求不是异步的?
-
也许你正在做的其他事情在
updateFromServer中被阻止 - 我无法从这里判断 -
我添加了完整的代码。看起来很正常……
标签: iphone objective-c multithreading asynchronous asihttprequest