views:

37

answers:

1

I have a thread that modifies a passed pointer to an object (which is alloc'd and retained in the calling thread) in a loop. If I put the pointer in the autorelease pool, I sometimes get errors because the object is being released when it shouldn't. I took it out of the autorelease pool and this seems to work. However, I am worried about a memory leak because if I don't use an autorelease pool at all, I get a severe leak.

-(void)my_thread:(NSArray*)parameters;
{       
    //keep this out of the autorelease pool
    Object *theObject;
    [[parameters objectAtIndex:2] getValue:&theObject];

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    //do stuff to theObject

    [pool release];
}
A: 

Given this:

-(void)my_thread:(NSArray*)parameters;
{       
...
}

The only way for parameters to be valid when said method is the entry point to a thread is if parameters has been retained by the spawning thread. Not retained and autoreleased, but simply retained.

In other words: autorelease pools can never contribute to thread safety. An autoreleased object can never traverse thread boundaries safely. There must be a hard retain of the object in the sending thread and the receiving thread must release said object. End of story.

Or codewise:

-(void)my_thread:(NSArray*)parameters;
{     
    ... do your stuff here, including your autorelease pool dance
    [parameters release];  
}
bbum
Thanks. I don't necessarily need to release parameters. I just need to know whether to include it in the autorelease pool or not. It sounds like I shouldn't, per your example. That makes sense if it's the case, I just want to be sure.
Synthetix
Parameters must be retained on entry. If you autorelease it or release it within the body of that method is entirely irrelevant, but you must do one or else there will be a leak.
bbum