iosautomatic-ref-countingautoreleasensautoreleasepool

Does @autoreleasepool make sense in my scenario and in ARC?


I parse the content of a file in order to create a set of NSManagedObject in a context and save them. This is the method where I do this:

- (BOOL)getEntitiesFromFileInContext:(NSManagedObjectContext *)context
{
   BOOL result = YES;
   NSMutableArray *entities = [[NSMutableArray alloc] init];

   NSString *entitiesFileContent = [FilesManagerHelper readFile:fileName];

   if ([entitiesFileContent isEqualToString:@""]) {
       result = NO;
   }
   else {
       @autoreleasepool {
           entities = [self parseEntitiesFileContent:entitiesFileContent inContext:context];

           // If entities.count > 0, some operations here
       }

       // Save context and reset
       [self saveContext:context];
       [self clearContext:context];
   }

   return result;
}

In parseEntitiesFileContent:inContext: method I insert the NSManagedObject objects in the context I provide and I also add them to the entities array.

I'm performing this in an @autoreleasepool because I found an example doing that, but I'm not sure if it is really necessary... Could somebody explain me what the difference between using @autoreleasepool and not using it should be?

Thanks so much

EDIT: Should the entities array be defined inside the @autoreleasepool block?


Solution

  • Because entities is declared within the scope of the method but not in the autorelease pool block, you have a strong pointer to entities outside the autorelease pool block and the auto release pool in this case will have no effect.

    To verify this try logging entities just before the method returns.

    For the auto release pool block to have some meaning, declare entities within the auto release pool block.

    @autoreleasepool {
           NSMutableArray *entities = [self parseEntitiesFileContent:entitiesFileContent inContext:context];
    
           // If entities.count > 0, some operations here
       }
    

    Now try and log entities straight after the auto release pool block.

    This case is rather trivial if entities is small, however it is not a bad to include as it may help with scalability as this method may evolve over time and the auto release block starts to do more. If entities can be potentially large then you most definitely want the pool. My advice is to leave the auto release pool block and move the declaration of entities inside the pool block.