1

我在 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
}

来源例如: http: //pastebin.com/3z5SM4R0

4

1 回答 1

5

不,该代码不会导致堆栈溢出,因为每次调用都不会在当前堆栈上推送新的堆栈帧。

在 C(以及 Objective-C)中,当您调用函数时,“堆栈帧”被“推入堆栈”。堆栈帧包含函数调用的数据,如函数参数和返回地址(除其他外)。该信息占用空间,因此强制执行最大堆栈深度。

每次调用函数时,都会“推送”一个堆栈帧。每次函数返回时,都会“弹出”一个堆栈帧。要可视化问题,请参阅以下方法:

- (void)overflow
{
     NSLog(@"Pushing...");
     [self overflow];
     NSLog(@"Popping...");
}

那将打印:

Pushing...  
Pushing...  
Pushing...  
Pushing...  
... (etc until overflow).

如您所见,该函数永远不会返回。每次递归时,它都会推送另一个堆栈帧。

您发布的示例的不同之处在于该方法不直接调用自身。它使用该performSelectorInBackground:withObject:方法,该方法不会立即调用该方法。它将它安排在另一个线程¹(使用另一个调用堆栈)上,然后立即返回。所以,回顾一下前面的例子:

- (void)overflow
{
     NSLog(@"Pushing...");
     [self performSelectorInBackground:@selector(overflow) withObject:nil];
     NSLog(@"Popping...");
}

现在将打印:

Pushing...  
Popping...
Pushing...
Popping...
Pushing...
Popping...
... (etc forever).

因此,您可以看到第二个示例通过异步调度递归来保持平衡堆栈,而不是在自己的线程上同步调用它。


¹根据文档

于 2013-07-08T20:47:37.493 回答