【发布时间】:2013-07-08 20:30:11
【问题描述】:
我在 pastebin 上看到了一个长轮询技术的示例,我想知道设计的递归性质是否会导致堆栈溢出?抱歉,如果这是一个菜鸟问题,但我不熟悉长轮询,我对 Objective-c 也不是很熟悉。
//long polling in objective-C
- (void) longPoll {
//create an autorelease pool for the thread
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
//compose the request
NSError* error = nil;
NSURLResponse* response = nil;
NSURL* requestUrl = [NSURL URLWithString:@"http://www.example.com/pollUrl"];
NSURLRequest* request = [NSURLRequest requestWithURL:requestUrl];
//send the request (will block until a response comes back)
NSData* responseData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response error:&error];
//pass the response on to the handler
//(can also check for errors here, if you want)
[self performSelectorOnMainThread:@selector(dataReceived:)
withObject:responseData waitUntilDone:YES];
//clear the pool
[pool drain];
//send the next poll request
[self performSelectorInBackground:@selector(longPoll) withObject: nil];
}
- (void) startPoll {
//not covered in this example:
// -stopping the poll
// -ensuring that only 1 poll is active at any given time
[self performSelectorInBackground:@selector(longPoll) withObject: nil];
}
- (void) dataReceived: (NSData*) theData {
//process the response here
}
【问题讨论】:
-
它可能不会破坏堆栈,但是男孩你好,它会产生很多线程,这有时非常非常昂贵。
-
@CodaFi 所以每次递归都会产生一个新线程?
-
这是一个实现细节。我相信如果有机会它可能会,但希望他们变得更聪明并在 GCD 之上实现它。选择器已经在后台执行,只需将其设置为延迟,它将继续在同一个线程上被调用。更好的是,将其重构为 NSOperation 并创建一个私有队列。您将能够更轻松地调试任何故障。
标签: ios objective-c http stack-overflow long-polling