Usage of autorelease pool in objectAtindex swizzling for NSMutableArray

85 Views Asked by At
- (nullable id)myObjectAtIndex:(NSUInteger)index{
    @autoreleasepool {
        id value = nil;
        if (index < self.count)
        {
            value = [self myObjectAtIndex:index];
        }
        return value;
    }

}

I have no idea about the purpose of using autoreleasepool here. Can someone give me a hand?

2

There are 2 best solutions below

1
On

Unless I'm missing the obvious, which is always possible, we can only guess:

There is a stack of autorelease pools, the top of the stack being the one in use. When the @autoreleasepool { ... } construct is entered a new pool is created and pushed on the stack, on exit from the construct the pool is drained and popped off the stack.

The reason to create local pools is given in the NSAutoReleasePool docs (emphasis added):

The Application Kit creates an autorelease pool on the main thread at the beginning of every cycle of the event loop, and drains it at the end, thereby releasing any autoreleased objects generated while processing an event. If you use the Application Kit, you therefore typically don’t have to create your own pools. If your application creates a lot of temporary autoreleased objects within the event loop, however, it may be beneficial to create “local” autorelease pools to help to minimize the peak memory footprint.

So what is the purpose in the code you are looking at? Some guesses:

  • Either the original author knows/believes that the called methods count and objectAtIndex (post the swizzle) add a significant amount of objects to the autorelease pool and wishes to clean these up; or

  • The original author was/is planning to add future code to myObjectAtIndex which will add a significant amount of objects to the autorelease pool and wishes to clean these up; or

  • Wishes to be able to call objectAtIndex and ensure there is no impact on the memory used for live objects (e.g. maybe they were measuring memory use by something else); or

  • Who knows, accept the original author (hopefully!)

HTH

5
On

There is no scientific reason.

The whole code is an example of "this app crashes and I do not know why" panic code:

Obviously the author had a problem with guaranteeing correct indexes, what would be the correct approach. Therefore he wrote a special method to "repair" it. The naming ("my") shows, that he thought: I can do it better (instead of insuring correct indexes).

Moreover, adding an ARP to a piece of code, that obviously does not create an bigger amount of objects, is a sure sign for the fact, that he couldn't oversee his code anymore.

Move the whole code to /dev/null.