Where to put autoreleasepool?

In another thread about NSDate memory leak, I learned that sometimes I need to wrap code inside an @autoreleasepool. But I get more puzzled when I really try to refactor my code.


Here is my problem. I have a NSCondition dervived class which implements a convenience method:

- (BOOL)wait:(NSTimeInterval)timeToWait
{
    NSDate* date = [[NSDate date] dateByAddingTimeInterval:timeToWait];
    BOOL f = [self waitUntilDate:date];
    return f;
}

In some place, I need to poll on something (don't argue with me about disadvantages about polling):

- (void)monitor
{
    while (YES)
    {
        [_guard lock];
        if(_guard.stop)
        {
            break;
        }
        [_guard wait:DEFAULT_POLL_INTERVAL];
        [self check_visibility];
        [_guard unlock];
    }
}

Now I'm bewildered about where to put @autoreleasepool, in the outer loop or directly in the wait: method.


Thanks for any suggestions.

There's no absolute answer. The logical place to do it would be within the while loop:


     while (YES) {
          @autoreleasepool {
               …
          }
     }


because that will prevent the build-up of unreferenced, autoreleased objects from anywhere inside the loop. That's mostly safe — even if an object "escapes" the loop (gains a reference outside the loop), the pool drain won't affect it.


However, there are a few situations where it's not safe. The most common is when you have a method that returns a NSError object, so the parameter looks like this:


     - (…) someMethod… error: (NSError**) outError {


If you accidentally create a NSError object in a local autorelease pool, it won't survive a pool drain, possibly leading to inexplicable crashes.


So, I won't argue with you about the disadvantages of polling, but I will point out that this sort of complication with memory management is one consequence of using that sort of approach.

It seems @autoreleasepool can be nested and it also affects code in a called method. Right?

Now I have to wrap @autoreleasepool around a very long body of while {} bock. I kind of don't like this in that it make code very unreadable.


BTW, does Objective-C support nested function?

>does Objective-C support nested function


See the 1st answer/reply in this SO thread...


https://stackoverflow.com/questions/9054576/can-a-c-function-be-defined-within-an-objective-c-method

Where to put autoreleasepool?
 
 
Q