1

Ok, so my question is something I have been looking for for a while. Say the method "first" has been detached as a new thread.

-(void)first{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    int a;
    NSMutableArray *array = [self getArray];
    [pool drain];
}

-(NSMutableArray *)getArray{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSMutableArray *ar = [NSMutableArray array];
    [ar addObject:[NSString stringWithString:@"Hello"]];
    return ar;
    [pool drain];
}

My issue is that if i drain the pool after the object is returned, the pool doesnt get drained, and its leaked, however if i drain it before i return the array i cannot release the array because obviously its going to be needed...

This may be something thats really obvious, and i'm just missing but i am really confused. Thanks in advance.

Chance Hudson
  • 2,849
  • 1
  • 19
  • 22

1 Answers1

2

It is unnecessary to have a second autorelease pool in the getArray method.

If, for some reason, you wanted to have an ARP in the getArray method, you'd probably implement it like this:

- (NSMutableArray *)getArray {
  NSMutableArray *ar = [NSMutableArray array];
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  //do stuff
  [pool drain];
  return ar;
}

You technically can leave the pool un-drained, and it will get drained automatically when a "higher" pool gets drained, but IMO that's a sign of some really poorly designed code.

Dave DeLong
  • 242,470
  • 58
  • 448
  • 498
  • Ok, so having to use a nonvoid function in a thread like this is generally considered bad code design? – Chance Hudson May 25 '11 at 06:45
  • @user397313 you can use any sort of method you want within a thread. The only stipulation is that the entry method must have a `void` return type, because there's nothing you *can* return. – Dave DeLong May 25 '11 at 17:23
  • oh, i think you are misunderstanding, and i am coding wrong. I think my issue was putting a second NSAutoreleasePool inside this. The nonvoid method was not detached as a thread, but was called from the second thread. – Chance Hudson May 26 '11 at 23:08